e66a8182c4476ef18b46c6ecc53a34433e7d342f
[nonrtric.git] / dmaap-mediator-producer / internal / config / config_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package config
22
23 import (
24         "bytes"
25         "encoding/json"
26         "os"
27         "path/filepath"
28         "testing"
29
30         log "github.com/sirupsen/logrus"
31         "github.com/stretchr/testify/require"
32 )
33
34 func TestNew_envVarsSetConfigContainSetValues(t *testing.T) {
35         assertions := require.New(t)
36         os.Setenv("LOG_LEVEL", "Debug")
37         os.Setenv("INFO_PRODUCER_HOST", "producerHost")
38         os.Setenv("INFO_PRODUCER_PORT", "8095")
39         os.Setenv("INFO_COORD_ADDR", "infoCoordAddr")
40         os.Setenv("DMAAP_MR_ADDR", "mrHost:3908")
41         os.Setenv("KAFKA_BOOTSTRAP_SERVERS", "localhost:9093")
42         os.Setenv("PRODUCER_CERT_PATH", "cert")
43         os.Setenv("PRODUCER_KEY_PATH", "key")
44         t.Cleanup(func() {
45                 os.Clearenv()
46         })
47         wantConfig := Config{
48                 LogLevel:               log.DebugLevel,
49                 InfoProducerHost:       "producerHost",
50                 InfoProducerPort:       8095,
51                 InfoCoordinatorAddress: "infoCoordAddr",
52                 DMaaPMRAddress:         "mrHost:3908",
53                 KafkaBootstrapServers:  "localhost:9093",
54                 ProducerCertPath:       "cert",
55                 ProducerKeyPath:        "key",
56         }
57         got := New()
58
59         assertions.Equal(&wantConfig, got)
60 }
61
62 func TestNew_faultyIntValueSetConfigContainDefaultValueAndWarnInLog(t *testing.T) {
63         assertions := require.New(t)
64         var buf bytes.Buffer
65         log.SetOutput(&buf)
66
67         os.Setenv("INFO_PRODUCER_PORT", "wrong")
68         t.Cleanup(func() {
69                 log.SetOutput(os.Stderr)
70                 os.Clearenv()
71         })
72         wantConfig := Config{
73                 LogLevel:               log.InfoLevel,
74                 InfoProducerHost:       "",
75                 InfoProducerPort:       8085,
76                 InfoCoordinatorAddress: "https://informationservice:8434",
77                 DMaaPMRAddress:         "https://message-router.onap:3905",
78                 KafkaBootstrapServers:  "localhost:9092",
79                 ProducerCertPath:       "security/producer.crt",
80                 ProducerKeyPath:        "security/producer.key",
81         }
82         got := New()
83         assertions.Equal(&wantConfig, got)
84         logString := buf.String()
85         assertions.Contains(logString, "Invalid int value: wrong for variable: INFO_PRODUCER_PORT. Default value: 8085 will be used")
86 }
87
88 func TestNew_envFaultyLogLevelConfigContainDefaultValues(t *testing.T) {
89         assertions := require.New(t)
90         var buf bytes.Buffer
91         log.SetOutput(&buf)
92
93         os.Setenv("LOG_LEVEL", "wrong")
94         t.Cleanup(func() {
95                 log.SetOutput(os.Stderr)
96                 os.Clearenv()
97         })
98
99         wantConfig := Config{
100                 LogLevel:               log.InfoLevel,
101                 InfoProducerHost:       "",
102                 InfoProducerPort:       8085,
103                 InfoCoordinatorAddress: "https://informationservice:8434",
104                 DMaaPMRAddress:         "https://message-router.onap:3905",
105                 KafkaBootstrapServers:  "localhost:9092",
106                 ProducerCertPath:       "security/producer.crt",
107                 ProducerKeyPath:        "security/producer.key",
108         }
109
110         got := New()
111
112         assertions.Equal(&wantConfig, got)
113         logString := buf.String()
114         assertions.Contains(logString, "Invalid log level: wrong. Log level will be Info!")
115 }
116
117 const typeDefinition = `{"types": [{"id": "type1", "dmaapTopicUrl": "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1"}, {"id": "type2", "kafkaInputTopic": "TestTopic"}]}`
118 const typeSchemaFileContent = `{
119         "$schema": "http://json-schema.org/draft-04/schema#",
120         "type": "object",
121         "properties": {
122           "filter": {
123                  "type": "string"
124            }
125         },
126         "additionalProperties": false
127   }`
128
129 func TestGetTypesFromConfiguration_fileOkShouldReturnSliceOfTypeDefinitions(t *testing.T) {
130         assertions := require.New(t)
131         typesDir, err := os.MkdirTemp("", "configs")
132         if err != nil {
133                 t.Errorf("Unable to create temporary directory for types due to: %v", err)
134         }
135         fname := filepath.Join(typesDir, "type_config.json")
136         t.Cleanup(func() {
137                 os.RemoveAll(typesDir)
138         })
139         if err = os.WriteFile(fname, []byte(typeDefinition), 0666); err != nil {
140                 t.Errorf("Unable to create temporary config file for types due to: %v", err)
141         }
142         fname = filepath.Join(typesDir, "typeSchemaDmaap.json")
143         if err = os.WriteFile(fname, []byte(typeSchemaFileContent), 0666); err != nil {
144                 t.Errorf("Unable to create temporary schema file for DMaaP type due to: %v", err)
145         }
146         fname = filepath.Join(typesDir, "typeSchemaKafka.json")
147         if err = os.WriteFile(fname, []byte(typeSchemaFileContent), 0666); err != nil {
148                 t.Errorf("Unable to create temporary schema file for Kafka type due to: %v", err)
149         }
150         var typeSchemaObj interface{}
151         json.Unmarshal([]byte(typeSchemaFileContent), &typeSchemaObj)
152
153         types, err := GetJobTypesFromConfiguration(typesDir)
154
155         wantedDMaaPType := TypeDefinition{
156                 Identity:      "type1",
157                 DMaaPTopicURL: "events/unauthenticated.SEC_FAULT_OUTPUT/dmaapmediatorproducer/type1",
158                 TypeSchema:    typeSchemaObj,
159         }
160         wantedKafkaType := TypeDefinition{
161                 Identity:        "type2",
162                 KafkaInputTopic: "TestTopic",
163                 TypeSchema:      typeSchemaObj,
164         }
165         wantedTypes := []TypeDefinition{wantedDMaaPType, wantedKafkaType}
166         assertions.EqualValues(wantedTypes, types)
167         assertions.Nil(err)
168 }