6c98645823476db84eee58a6b779e59b970e411e
[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         "strings"
28         "testing"
29
30         "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"
33 )
34
35 const (
36         expectedHelmSearchCmd = "search helm-repo"
37         expectedHelmFetchCmd  = `fetch --untar --untardir /tmp helm-repo/dummy-xapp`
38 )
39
40 var caughtKubeExecArgs []string
41 var kubeExecRetOut string
42 var kubeExecRetErr error
43 var caughtHelmExecArgs string
44 var helmExecRetOut string
45 var helmExecRetErr error
46
47 var 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
55 var helmSearchOutput = `
56 helm-repo/anr           0.0.1           1.0             Helm Chart for Nokia ANR (Automatic Neighbour Relation) xAPP
57 helm-repo/appmgr        0.0.2           1.0             Helm Chart for xAppManager
58 helm-repo/dualco        0.0.1           1.0             Helm Chart for Nokia dualco xAPP
59 helm-repo/reporter      0.0.1           1.0             Helm Chart for Reporting xAPP
60 helm-repo/uemgr         0.0.1           1.0             Helm Chart for Nokia uemgr xAPP
61 `
62
63 var 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"],
76        "rxMessages": ["RIC_X2_LOAD_INFORMATION"],
77            "policies":   [11, 22, 33]
78     },
79     "db": {
80         "namespace": "ricxapp",
81         "host": "dbaas",
82         "port": 6379
83     }
84 }
85 `
86 var 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 `
178 var cfgData = `{
179         "active":true,
180         "interfaceId": {
181                 "globalENBId":{
182                         "plmnId": "1234",
183                         "eNBId":"55"
184                 }
185         }
186 }`
187
188 type ConfigSample struct {
189         Level int
190         Host  string
191 }
192
193 type MockedConfigMapper struct {
194 }
195
196 func (cm *MockedConfigMapper) ReadSchema(name string, c *models.XAppConfig) (err error) {
197         return
198 }
199
200 func (cm *MockedConfigMapper) UploadConfig() (cfg []models.XAppConfig) {
201         return
202 }
203
204 func (cm *MockedConfigMapper) UpdateConfigMap(r models.XAppConfig) (errList models.ConfigValidationErrors, err error) {
205         return
206 }
207
208 func (cm *MockedConfigMapper) ReadConfigMap(name string, ns string, c *interface{}) (err error) {
209         return
210 }
211
212 func (cm *MockedConfigMapper) FetchChart(name string) (err error) {
213         return
214 }
215
216 func (cm *MockedConfigMapper) GetRtmData(name string) (msgs appmgr.RtmData) {
217         return
218 }
219
220 func (cm *MockedConfigMapper) GetNamespace(ns string) (n string) {
221         return
222 }
223
224 func (cm *MockedConfigMapper) GetNamesFromHelmRepo() (names []string) {
225         return
226 }
227
228 // Test cases
229 func TestMain(m *testing.M) {
230         appmgr.Init()
231         appmgr.Logger.SetLevel(0)
232
233         code := m.Run()
234         os.Exit(code)
235 }
236
237 func 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
281 func 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
300 func 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
344 func 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
364 func TestGetRtmDataSuccess(t *testing.T) {
365         expectedKubeCmd := []string{
366                 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp  configmap-ricxapp-dummy-xapp-appconfig`,
367         }
368         expectedMsgs := appmgr.RtmData{
369                 TxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
370                 RxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
371                 Policies:   []int64{11, 22, 33},
372         }
373
374         defer func() { resetKubeExecMock() }()
375         kubeExec = mockedKubeExec
376         //Fake 'kubectl get configmap' success
377         kubeExecRetOut = kubectlConfigmapOutput
378
379         result := NewCM().GetRtmData("dummy-xapp")
380         if !reflect.DeepEqual(result, expectedMsgs) {
381                 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
388 func 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
412 func 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
426 func 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)
436         }
437 }
438
439 func 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
449 func TestFetchChartFails(t *testing.T) {
450         if NewCM().FetchChart("dummy-xapp") == nil {
451                 t.Errorf("TestFetchChart failed!")
452         }
453 }
454
455 func TestFetchChartSuccess(t *testing.T) {
456         defer func() { resetHelmExecMock() }()
457         helmExec = mockedHelmExec
458
459         if NewCM().FetchChart("dummy-xapp") != nil {
460                 t.Errorf("TestFetchChart failed!")
461         }
462 }
463
464 func 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
470 func TestGetNamespaceReturnsConfiguredNamespaceName(t *testing.T) {
471         if ns := NewCM().GetNamespace(""); ns != "ricxapp" {
472                 t.Errorf("GetNamespace failed: expected: ricxapp, got: %s", ns)
473         }
474 }
475
476 func TestGetNamesFromHelmRepoSuccess(t *testing.T) {
477         expectedResult := []string{"anr", "appmgr", "dualco", "reporter", "uemgr"}
478
479         defer func() { resetHelmExecMock() }()
480         helmExec = mockedHelmExec
481         //Fake helm search success
482         helmExecRetOut = helmSearchOutput
483
484         names := NewCM().GetNamesFromHelmRepo()
485         if !reflect.DeepEqual(names, expectedResult) {
486                 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
487         }
488         if caughtHelmExecArgs != expectedHelmSearchCmd {
489                 t.Errorf("GetNamesFromHelmRepo failed: expected: %v, got: %v", expectedHelmSearchCmd, caughtHelmExecArgs)
490         }
491 }
492
493 func TestGetNamesFromHelmRepoFailure(t *testing.T) {
494         expectedResult := []string{}
495
496         defer func() { resetHelmExecMock() }()
497         helmExec = mockedHelmExec
498         helmExecRetOut = helmSearchOutput
499         helmExecRetErr = errors.New("Command failed!")
500
501         names := NewCM().GetNamesFromHelmRepo()
502         if names != nil {
503                 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
504         }
505 }
506
507 func TestBuildConfigMapSuccess(t *testing.T) {
508         expectedKubeCmd := []string{
509                 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp  configmap-ricxapp-dummy-xapp-appconfig`,
510         }
511         name := "dummy-xapp"
512         namespace := "ricxapp"
513         m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
514         s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
515                 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
516
517         defer func() { resetKubeExecMock() }()
518         kubeExec = mockedKubeExec
519         //Fake 'kubectl get configmap' success
520         kubeExecRetOut = `{"logger": {"level": 2}}`
521
522         cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
523         if err != nil {
524                 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
525         }
526         if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubeCmd) {
527                 t.Errorf("BuildConfigMap failed: expected: %v, got: %v", expectedKubeCmd, caughtKubeExecArgs)
528         }
529 }
530
531 func TestBuildConfigMapReturnErrorIfJsonMarshalFails(t *testing.T) {
532         name := "dummy-xapp"
533         namespace := "ricxapp"
534         m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
535         //Give channel as a configuration input, this will fail JSON marshal
536         cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: make(chan int)})
537         if err == nil {
538                 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
539         }
540 }
541
542 func TestBuildConfigMapReturnErrorIfKubectlGetConfigmapFails(t *testing.T) {
543         name := "dummy-xapp"
544         namespace := "ricxapp"
545         m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
546         s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
547                 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
548
549         defer func() { resetKubeExecMock() }()
550         kubeExec = mockedKubeExec
551         //Fake 'kubectl get configmap' failure
552         kubeExecRetErr = errors.New("some error")
553
554         cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
555         if err == nil {
556                 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
557         } else if err.Error() != "some error" {
558                 t.Errorf("BuildConfigMap failed: expected: 'some error', got: '%s'", err.Error())
559         }
560 }
561
562 func TestBuildConfigMapReturnErrorIfJsonParserFails(t *testing.T) {
563         name := "dummy-xapp"
564         namespace := "ricxapp"
565         m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
566         s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
567                 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
568
569         defer func() { resetKubeExecMock() }()
570         kubeExec = mockedKubeExec
571         //Return empty json that causes JSON parser to fail
572         kubeExecRetOut = ``
573
574         cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
575         if err == nil {
576                 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
577         }
578 }
579
580 func TestGenerateJSONFileSuccess(t *testing.T) {
581         err := NewCM().GenerateJSONFile("{}")
582         if err != nil {
583                 t.Errorf("GenerateJSONFile failed: %v", err)
584         }
585 }
586
587 func TestReplaceConfigMapSuccess(t *testing.T) {
588         name := "dummy-xapp"
589         namespace := "ricxapp"
590
591         defer func() { resetKubeExecMock() }()
592         kubeExec = mockedKubeExec
593         //Fake 'kubectl create configmap' success
594         kubeExecRetOut = ""
595
596         err := NewCM().ReplaceConfigMap(name, namespace)
597         if err != nil {
598                 t.Errorf("ReplaceConfigMap failed: %v", err)
599         }
600 }
601
602 func TestUpdateConfigMapReturnsErrorIfSchemaFileIsMissing(t *testing.T) {
603         name := "dummy-xapp"
604         namespace := "ricxapp"
605         config := models.XAppConfig{Metadata: &models.ConfigMetadata{XappName: &name, Namespace: &namespace}}
606
607         defer func() { resetHelmExecMock() }()
608         helmExec = mockedHelmExec
609         helmExecRetOut = `{}`
610
611         //Will fail at schema reading, because schema file is mission
612         validationErrors, err := NewCM().UpdateConfigMap(config)
613         if err == nil {
614                 t.Errorf("UpdateConfigMap failed: %v -> %v", err, validationErrors)
615         }
616         if caughtHelmExecArgs != expectedHelmFetchCmd {
617                 t.Errorf("UpdateConfigMap failed: expected: %v, got: %v", expectedHelmFetchCmd, caughtHelmExecArgs)
618         }
619 }
620
621 func TestUpdateConfigMapReturnsErrorIfHelmFetchChartFails(t *testing.T) {
622         name := "dummy-xapp"
623         namespace := "ricxapp"
624         config := models.XAppConfig{Metadata: &models.ConfigMetadata{XappName: &name, Namespace: &namespace}}
625
626         defer func() { resetHelmExecMock() }()
627         helmExec = mockedHelmExec
628         helmExecRetErr = errors.New("some error")
629
630         validationErrors, err := NewCM().UpdateConfigMap(config)
631         if err == nil {
632                 t.Errorf("UpdateConfigMap failed: %v -> %v", err, validationErrors)
633         }
634 }
635
636 func TestValidationSuccess(t *testing.T) {
637         var d interface{}
638         var cfg map[string]interface{}
639         err := json.Unmarshal([]byte(`{"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
640
641         err = NewCM().ReadFile("../../test/schema.json", &d)
642         if err != nil {
643                 t.Errorf("ReadFile failed: %v -> %v", err, d)
644         }
645
646         feedback, err := NewCM().doValidate(d, cfg)
647         if err != nil {
648                 t.Errorf("doValidate failed: %v -> %v", err, feedback)
649         }
650 }
651
652 func TestValidationFails(t *testing.T) {
653         var d interface{}
654         var cfg map[string]interface{}
655
656         err := json.Unmarshal([]byte(`{"active": "INVALID", "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
657
658         err = NewCM().ReadFile("../../test/schema.json", &d)
659         if err != nil {
660                 t.Errorf("ConfigMetadata failed: %v -> %v", err, d)
661         }
662
663         feedback, err := NewCM().doValidate(d, cfg)
664         if err == nil {
665                 t.Errorf("doValidate should fail but didn't: %v -> %v", err, feedback)
666         }
667         appmgr.Logger.Debug("Feedbacks: %v", feedback)
668 }
669
670 func TestReadFileReturnsErrorIfFileReadFails(t *testing.T) {
671         var d interface{}
672
673         if err := NewCM().ReadFile("not/existing/test/schema.json", &d); err == nil {
674                 t.Errorf("ReadFile should fail but it didn't")
675         }
676 }
677
678 func TestReadFileReturnsErrorIfJsonUnmarshalFails(t *testing.T) {
679         var d interface{}
680
681         if err := NewCM().ReadFile("../../test/faulty_schema.json", &d); err == nil {
682                 t.Errorf("ReadFile should fail but it didn't")
683         }
684 }
685
686 func mockedKubeExec(args string) (out []byte, err error) {
687         caughtKubeExecArgs = append(caughtKubeExecArgs, args)
688         return []byte(kubeExecRetOut), kubeExecRetErr
689 }
690
691 func resetKubeExecMock() {
692         kubeExec = util.KubectlExec
693         caughtKubeExecArgs = nil
694         kubeExecRetOut = ""
695         kubeExecRetErr = nil
696 }
697
698 func mockedHelmExec(args string) (out []byte, err error) {
699         caughtHelmExecArgs = args
700         return []byte(helmExecRetOut), helmExecRetErr
701 }
702
703 func resetHelmExecMock() {
704         helmExec = util.HelmExec
705         caughtHelmExecArgs = ""
706         helmExecRetOut = ""
707         helmExecRetErr = nil
708 }