blob: 714936cc7d4380a087f80638dc671b9241729c15 [file] [log] [blame]
Matteo Scandolod2044a42017-08-07 16:08:28 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Matteo Scandolo56879722017-05-17 21:39:54 -070017import unittest
18from mock import patch
19import os
20from xosconfig import Config
21from xosconfig import Config as Config2
22
23basic_conf = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/confs/basic_conf.yaml")
24yaml_not_valid = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/confs/yaml_not_valid.yaml")
25invalid_format = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/confs/invalid_format.yaml")
26sample_conf = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/confs/sample_conf.yaml")
27
Matteo Scandolo1879ce72017-05-30 15:45:26 -070028small_schema = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/schemas/small_schema.yaml")
29
Matteo Scandolo56879722017-05-17 21:39:54 -070030services_list = {
31 "xos-ws": [],
32 "xos-db": [],
33}
34
35db_service = [
36 {
37 "ModifyIndex": 6,
38 "CreateIndex": 6,
39 "Node": "0152982c3159",
40 "Address": "172.19.0.2",
41 "ServiceID": "0d53ce210785:frontend_xos_db_1:5432",
42 "ServiceName": "xos-db",
43 "ServiceTags": [],
44 "ServiceAddress": "172.18.0.4",
45 "ServicePort": 5432,
46 "ServiceEnableTagOverride": "false"
47 }
48 ]
49
50class XOSConfigTest(unittest.TestCase):
51 """
52 Testing the XOS Config Module
53 """
54
Scott Bakerb641f902017-10-24 10:13:34 -070055 def setUp(self):
56 # In case some other testcase in nose has left config in an unclean state
57 Config.clear()
58
Matteo Scandolo56879722017-05-17 21:39:54 -070059 def tearDown(self):
60 # NOTE clear the config after each test
61 Config.clear()
62
63 def test_initialize_only_once(self):
64 """
65 [XOS-Config] Raise if initialized twice
66 """
67 with self.assertRaises(Exception) as e:
68 Config.init(sample_conf)
69 Config2.init(sample_conf)
70 self.assertEqual(e.exception.message, "[XOS-Config] Module already initialized")
71
72 def test_config_not_initialized(self):
73 """
74 [XOS-Config] Raise if accessing properties without initialization
75 """
76 with self.assertRaises(Exception) as e:
77 Config.get("database")
78 self.assertEqual(e.exception.message, "[XOS-Config] Module has not been initialized")
79
80 def test_missing_file_exception(self):
81 """
82 [XOS-Config] Raise if file not found
83 """
84 with self.assertRaises(Exception) as e:
85 Config.init("missing_conf")
86 self.assertEqual(e.exception.message, "[XOS-Config] Config file not found at: missing_conf")
87
88 def test_yaml_not_valid(self):
89 """
90 [XOS-Config] Raise if yaml is not valid
91 """
92 with self.assertRaises(Exception) as e:
93 Config.init(yaml_not_valid)
94 self.assertEqual(e.exception.message, "[XOS-Config] The config format is wrong: Unable to load any data from source yaml file")
95
96 def test_invalid_format(self):
97 """
98 [XOS-Config] Raise if format is not valid (we expect a dictionary)
99 """
100 with self.assertRaises(Exception) as e:
101 Config.init(invalid_format)
102 self.assertEqual(e.exception.message, "[XOS-Config] The config format is wrong: Schema validation failed:\n - Value '['I am', 'a yaml', 'but the', 'format is not', 'correct']' is not a dict. Value path: ''.")
103
104 def test_env_override(self):
105 """
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700106 [XOS-Config] the XOS_CONFIG_FILE environment variable should override the config_file
Matteo Scandolo56879722017-05-17 21:39:54 -0700107 """
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700108 os.environ["XOS_CONFIG_FILE"] = "env.yaml"
Matteo Scandolo56879722017-05-17 21:39:54 -0700109 with self.assertRaises(Exception) as e:
110 Config.init("missing_conf")
111 self.assertEqual(e.exception.message, "[XOS-Config] Config file not found at: env.yaml")
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700112 del os.environ["XOS_CONFIG_FILE"]
113
114 def test_schema_override(self):
115 """
116 [XOS-Config] the XOS_CONFIG_SCHEMA environment variable should override the config_schema
117 """
118 os.environ["XOS_CONFIG_SCHEMA"] = "env-schema.yaml"
119 with self.assertRaises(Exception) as e:
120 Config.init(basic_conf)
121 self.assertRegexpMatches(e.exception.message, '\[XOS\-Config\] Config schema not found at: (.+)env-schema\.yaml')
122 # self.assertEqual(e.exception.message, "[XOS-Config] Config schema not found at: env-schema.yaml")
123 del os.environ["XOS_CONFIG_SCHEMA"]
124
125 def test_schema_override_usage(self):
126 """
127 [XOS-Config] the XOS_CONFIG_SCHEMA should be used to validate a config
128 """
129 os.environ["XOS_CONFIG_SCHEMA"] = small_schema
130 with self.assertRaises(Exception) as e:
131 Config.init(basic_conf)
132 self.assertEqual(e.exception.message, "[XOS-Config] The config format is wrong: Schema validation failed:\n - Key 'database' was not defined. Path: ''.")
133 del os.environ["XOS_CONFIG_SCHEMA"]
Matteo Scandolo56879722017-05-17 21:39:54 -0700134
135 def test_get_cli_param(self):
136 """
137 [XOS-Config] Should read CLI -C param
138 """
139 args = ["-A", "Foo", "-c", "Bar", "-C", "config.yaml"]
140 res = Config.get_cli_param(args)
141 self.assertEqual(res, "config.yaml")
142
143 def test_get_default_val_for_missing_param(self):
144 """
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700145 [XOS-Config] Should get the default value if nothing is specified
Matteo Scandolo56879722017-05-17 21:39:54 -0700146 """
147 Config.init(basic_conf)
148 log = Config.get("logging")
149 self.assertEqual(log, {
Scott Bakerb641f902017-10-24 10:13:34 -0700150 'version': 1,
151 'handlers': {
152 'console': {
153 'class': 'logging.StreamHandler',
154 },
155 'file': {
156 'class': 'logging.handlers.RotatingFileHandler',
157 'filename': '/var/log/xos.log',
158 'maxBytes': 10485760,
159 'backupCount': 5
160 }
161 },
162 'loggers': {
163 '': {
164 'handlers': ['console', 'file'],
165 'level': 'DEBUG'
166 }
167 }
Matteo Scandolo56879722017-05-17 21:39:54 -0700168 })
169
Matteo Scandoloe0fc6852017-06-07 16:01:54 -0700170 def test_get_config_file(self):
171 """
172 [XOS-Config] Should return the config file in use
173 """
174 Config.init(sample_conf)
175 res = Config.get_config_file()
176 self.assertEqual(res, sample_conf)
177
178 def test_get_missing_param(self):
Matteo Scandolo56879722017-05-17 21:39:54 -0700179 """
180 [XOS-Config] Should raise reading a missing param
181 """
182 Config.init(sample_conf)
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700183 res = Config.get("foo")
184 self.assertEqual(res, None)
Matteo Scandolo56879722017-05-17 21:39:54 -0700185
186 def test_get_first_level(self):
187 """
188 [XOS-Config] Should return a first level param
189 """
190 Config.init(sample_conf)
191 # NOTE we are using Config2 here to be sure that the configuration is readable from any import,
192 # not only from the one that has been used to initialize it
193 res = Config2.get("database")
194 self.assertEqual(res, {
Matteo Scandolo6bc017c2017-05-25 18:37:42 -0700195 "name": "xos",
Matteo Scandolo56879722017-05-17 21:39:54 -0700196 "username": "test",
197 "password": "safe"
198 })
199
200 def _test_get_child_level(self):
201 """
202 [XOS-Config] Should return a child level param
203 """
204 Config.init(sample_conf)
205 res = Config.get("nested.parameter.for")
206 self.assertEqual(res, "testing")
207
208 def test_get_service_list(self):
209 """
210 [XOS-Config] Should query registrator and return a list of services
211 """
212 with patch("xosconfig.config.requests.get") as mock_get:
213 mock_get.return_value.json.return_value = services_list
214 res = Config.get_service_list()
215 self.assertEqual(res, [
216 "xos-ws",
217 "xos-db",
218 ])
219
220 def test_get_service_info(self):
221 """
222 [XOS-Config] Should query registrator and return service info
223 """
224 with patch("xosconfig.config.requests.get") as mock_get:
225 mock_get.return_value.json.return_value = db_service
226 info = Config.get_service_info("xos-db")
227 self.assertEqual(info, {
228 "name": "xos-db",
229 "url": "172.18.0.4",
230 "port": 5432
231 })
232
233 def test_fail_get_service_info(self):
234 """
235 [XOS-Config] Should query registrator and return an exception if it"s down
236 """
237 with patch("xosconfig.config.requests.get") as mock_get:
238 mock_get.return_value.ok = False
239 with self.assertRaises(Exception) as e:
240 Config.get_service_info("missing-service")
241 self.assertEqual(e.exception.message, "[XOS-Config] Registrator is down")
242
243 def test_missing_get_service_info(self):
244 """
245 [XOS-Config] Should query registrator and return an exception if service is not there
246 """
247 with patch("xosconfig.config.requests.get") as mock_get:
248 mock_get.return_value.json.return_value = []
249 with self.assertRaises(Exception) as e:
250 Config.get_service_info("missing-service")
251 self.assertEqual(e.exception.message, "[XOS-Config] The service missing-service looking for does not exist")
252
253
254 def test_get_service_endpoint(self):
255 """
256 [XOS-Config] Should query registrator and return service endpoint
257 """
258 with patch("xosconfig.config.requests.get") as mock_get:
259 mock_get.return_value.json.return_value = db_service
260 endpoint = Config.get_service_endpoint("xos-db")
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700261 self.assertEqual(endpoint, "http://172.18.0.4:5432")
262
263
264if __name__ == '__main__':
265 unittest.main()