[PMSH] Update to package version and url for Postgres
[dcaegen2/services.git] / components / pm-subscription-handler / tests / test_pmsh_utils.py
1 # ============LICENSE_START===================================================
2 #  Copyright (C) 2019-2021 Nordix 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 # SPDX-License-Identifier: Apache-2.0
17 # ============LICENSE_END=====================================================
18 from test.support import EnvironmentVarGuard
19 from unittest.mock import patch, Mock
20
21 import responses
22 from jsonschema import ValidationError
23 from requests import Session
24 from tenacity import RetryError
25
26 from mod import get_db_connection_url
27 from mod.network_function import NetworkFunction
28 from tests.base_setup import BaseClassSetup
29 from tests.base_setup import get_pmsh_config
30
31
32 class PmshUtilsTestCase(BaseClassSetup):
33
34     @classmethod
35     def setUpClass(cls):
36         super().setUpClass()
37
38     def setUp(self):
39         super().setUp()
40         self.mock_app = Mock()
41
42     def tearDown(self):
43         super().tearDown()
44
45     @classmethod
46     def tearDownClass(cls):
47         super().tearDownClass()
48
49     def test_utils_get_mr_sub(self):
50         mr_policy_sub = self.app_conf.get_mr_sub('policy_pm_subscriber')
51         self.assertTrue(mr_policy_sub.aaf_id, 'dcae@dcae.onap.org')
52
53     def test_utils_get_mr_sub_fails_with_invalid_name(self):
54         with self.assertRaises(KeyError):
55             self.app_conf.get_mr_sub('invalid_sub')
56
57     def test_utils_get_mr_pub(self):
58         mr_policy_pub = self.app_conf.get_mr_pub('policy_pm_publisher')
59         self.assertTrue(mr_policy_pub.aaf_pass, 'demo123456!')
60
61     def test_utils_get_mr_pub_fails_with_invalid_name(self):
62         with self.assertRaises(KeyError):
63             self.app_conf.get_mr_pub('invalid_pub')
64
65     def test_utils_get_cert_data(self):
66         self.assertEqual(self.app_conf.cert_params, ('/opt/app/pmsh/etc/certs/cert.pem',
67                                                      '/opt/app/pmsh/etc/certs/key.pem'))
68
69     @patch.object(Session, 'post')
70     def test_mr_pub_publish_to_topic_success(self, mock_session):
71         mock_session.return_value.status_code = 200
72         mr_policy_pub = self.app_conf.get_mr_pub('policy_pm_publisher')
73         with patch('requests.Session.post') as session_post_call:
74             mr_policy_pub.publish_to_topic({"dummy_val": "43c4ee19-6b8d-4279-a80f-c507850aae47"})
75             session_post_call.assert_called_once()
76
77     @responses.activate
78     def test_mr_pub_publish_to_topic_fail(self):
79         responses.add(responses.POST,
80                       'https://message-router:3905/events/org.onap.dmaap.mr.PM_SUBSCRIPTIONS',
81                       json={'error': 'Client Error'}, status=400)
82         mr_policy_pub = self.app_conf.get_mr_pub('policy_pm_publisher')
83         with self.assertRaises(Exception):
84             mr_policy_pub.publish_to_topic({"dummy_val": "43c4ee19-6b8d-4279-a80f-c507850aae47"})
85
86     def test_mr_pub_publish_sub_event_data_success(self):
87         mr_policy_pub = self.app_conf.get_mr_pub('policy_pm_publisher')
88         with patch('mod.pmsh_utils._MrPub.publish_to_topic') as pub_to_topic_call:
89             mr_policy_pub.publish_subscription_event_data(
90                 self.app_conf.subscription,
91                 NetworkFunction(nf_name='pnf_1',
92                                 model_invariant_id='some-id',
93                                 model_version_id='some-id'),
94                 self.app_conf)
95             pub_to_topic_call.assert_called_once()
96
97     @responses.activate
98     def test_mr_sub_get_from_topic_success(self):
99         policy_mr_sub = self.app_conf.get_mr_sub('policy_pm_subscriber')
100         responses.add(responses.GET,
101                       'https://message-router:3905/events/org.onap.dmaap.mr.PM_SUBSCRIPTIONS/'
102                       'dcae_pmsh_cg/1?timeout=1000',
103                       json={"dummy_val": "43c4ee19-6b8d-4279-a80f-c507850aae47"}, status=200)
104         mr_topic_data = policy_mr_sub.get_from_topic(1)
105         self.assertIsNotNone(mr_topic_data)
106
107     @responses.activate
108     def test_mr_sub_get_from_topic_fail(self):
109         policy_mr_sub = self.app_conf.get_mr_sub('policy_pm_subscriber')
110         responses.add(responses.GET,
111                       'https://message-router:3905/events/org.onap.dmaap.mr.PM_SUBSCRIPTIONS/'
112                       'dcae_pmsh_cg/1?timeout=1000',
113                       json={"dummy_val": "43c4ee19-6b8d-4279-a80f-c507850aae47"}, status=400)
114         with self.assertRaises(Exception):
115             policy_mr_sub.get_from_topic(1)
116
117     def test_get_db_connection_url_success(self):
118         self.env = EnvironmentVarGuard()
119         self.env.set('PMSH_PG_URL', '1.2.3.4')
120         self.env.set('PMSH_PG_USERNAME', 'pmsh')
121         self.env.set('PMSH_PG_PASSWORD', 'pass')
122         db_url = get_db_connection_url()
123         self.assertEqual(db_url, 'postgresql+psycopg2://pmsh:pass@1.2.3.4:5432/pmsh')
124
125     def test_get_db_connection_url_fail(self):
126         self.env = EnvironmentVarGuard()
127         self.env.set('PMSH_PG_USERNAME', 'pmsh')
128         self.env.set('PMSH_PG_PASSWORD', 'pass')
129         with self.assertRaises(Exception):
130             get_db_connection_url()
131
132     @patch('mod.logger.info')
133     @patch('mod.pmsh_utils.get_all')
134     def test_refresh_config_success(self, mock_cbs_client_get_all, mock_logger):
135         mock_cbs_client_get_all.return_value = get_pmsh_config()
136         self.app_conf.refresh_config()
137         mock_logger.assert_called_with('AppConfig data has been refreshed')
138
139     @patch('mod.logger.error')
140     @patch('mod.pmsh_utils.get_all')
141     def test_refresh_config_fail(self, mock_cbs_client_get_all, mock_logger):
142         mock_cbs_client_get_all.side_effect = ValueError
143         with self.assertRaises(RetryError):
144             self.app_conf.refresh_config()
145         mock_logger.assert_called_with('Failed to refresh PMSH AppConfig')
146
147     @patch('mod.logger.debug')
148     def test_utils_validate_config_subscription(self, mock_logger):
149         self.app_conf.validate_sub_schema()
150         mock_logger.assert_called_with("Subscription schema is valid.")
151
152     @patch('mod.logger.debug')
153     def test_utils_validate_config_subscription_administrativeState_locked(self, mock_logger):
154         self.app_conf.subscription.administrativeState = "LOCKED"
155         self.app_conf.validate_sub_schema()
156         mock_logger.assert_called_with("Subscription schema is valid.")
157
158     def test_utils_validate_config_subscription_administrativeState_invalid_value(self):
159         self.app_conf.subscription.administrativeState = "FAILED"
160         with self.assertRaises(ValidationError):
161             self.app_conf.validate_sub_schema()
162
163     def test_utils_validate_config_subscription_nfFilter_failed(self):
164         self.app_conf.subscription.nfFilter = {}
165         with self.assertRaises(ValidationError):
166             self.app_conf.validate_sub_schema()
167
168     def test_utils_validate_config_subscription_nfFilter_not_empty(self):
169         self.app_conf.subscription.nfFilter = {
170             "nfNames": [
171
172             ],
173             "modelInvariantIDs": [
174
175             ],
176             "modelVersionIDs": [
177
178             ],
179             "modelNames": [
180
181             ]
182         }
183         with self.assertRaises(ValidationError):
184             self.app_conf.validate_sub_schema()
185
186     @patch('mod.logger.debug')
187     def test_utils_validate_config_subscription_nfFilter_with_empty_property(self, mock_logger):
188         self.app_conf.subscription.nfFilter = {
189             "nfNames": [
190                 "^pnf.*",
191                 "^vnf.*"
192             ],
193             "modelInvariantIDs": [
194                 "7129e420-d396-4efb-af02-6b83499b12f8"
195             ],
196             "modelVersionIDs": [
197
198             ],
199             "modelNames": [
200                 "pnf102"
201             ]
202         }
203         self.app_conf.validate_sub_schema()
204         mock_logger.assert_called_with("Subscription schema is valid.")
205
206     def test_utils_validate_config_subscription_where_measurementTypes_is_empty(self):
207         self.app_conf.subscription.measurementGroups = [{
208             "measurementGroup": {
209                 "measurementTypes": [
210                 ],
211                 "managedObjectDNsBasic": [
212                     {
213                         "DN": "dna"
214                     },
215                     {
216                         "DN": "dnb"
217                     }
218                 ]
219             }
220         }]
221         with self.assertRaises(ValidationError):
222             self.app_conf.validate_sub_schema()
223
224     def test_utils_validate_config_subscription_where_managedObjectDNsBasic_is_empty(self):
225         self.app_conf.subscription.measurementGroups = [{
226             "measurementGroup": {
227                 "measurementTypes": [
228                     {
229                         "measurementType": "countera"
230                     },
231                     {
232                         "measurementType": "counterb"
233                     }
234                 ],
235                 "managedObjectDNsBasic": [
236
237                 ]
238             }
239         }]
240         with self.assertRaises(ValidationError):
241             self.app_conf.validate_sub_schema()
242
243     def test_utils_validate_config_subscription_where_measurementGroups_is_empty(self):
244         self.app_conf.subscription.measurementGroups = []
245         with self.assertRaises(ValidationError):
246             self.app_conf.validate_sub_schema()