Refactored the Aodh notifier class
[osm/MON.git] / osm_mon / test / OpenStack / test_notifier.py
1 # Copyright 2017 Intel Research and Development Ireland Limited
2 # *************************************************************
3
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Intel Corporation
6
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # 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, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact: helena.mcgough@intel.com or adrian.hoban@intel.com
21 ##
22 """Tests for all common OpenStack methods."""
23
24 import json
25
26 import unittest
27
28 from BaseHTTPServer import BaseHTTPRequestHandler
29
30 from core.message_bus.producer import KafkaProducer
31
32 import mock
33
34 from plugins.OpenStack.Aodh.alarming import Alarming
35 from plugins.OpenStack.common import Common
36 from plugins.OpenStack.response import OpenStack_Response
37 from plugins.OpenStack.settings import Config
38
39 __author__ = "Helena McGough"
40
41 # Mock data from post request
42 post_data = json.dumps({"severity": "critical",
43 "alarm_name": "my_alarm",
44 "current": "current_state",
45 "alarm_id": "my_alarm_id",
46 "reason": "Threshold has been broken",
47 "reason_data": {"count": 1,
48 "most_recent": "null",
49 "type": "threshold",
50 "disposition": "unknown"},
51 "previous": "previous_state"})
52
53 valid_get_resp = '{"gnocchi_resources_threshold_rule":\
54 {"resource_id": "my_resource_id"}}'
55
56 invalid_get_resp = '{"gnocchi_resources_threshold_rule":\
57 {"resource_id": "None"}}'
58
59 valid_notify_resp = '{"notify_details": {"status": "current_state",\
60 "severity": "critical",\
61 "resource_uuid": "my_resource_id",\
62 "alarm_uuid": "my_alarm_id",\
63 "vim_type": "OpenStack",\
64 "start_date": "dd-mm-yyyy 00:00"},\
65 "schema_version": "1.0",\
66 "schema_type": "notify_alarm"}'
67
68 invalid_notify_resp = '{"notify_details": {"invalid":"mock_details"}'
69
70
71 class Response(object):
72 """Mock a response class for generating responses."""
73
74 def __init__(self, text):
75 """Initialise a mock response with a text attribute."""
76 self.text = text
77
78
79 class NotifierHandler(BaseHTTPRequestHandler):
80 """Mock the NotifierHandler class for testing purposes."""
81
82 def __init__(self, request, client_address, server):
83 """Initilase mock NotifierHandler."""
84 self.request = request
85 self.client_address = client_address
86 self.server = server
87 self.setup()
88 try:
89 self.handle()
90 finally:
91 self.finish()
92
93 def setup(self):
94 """Mock setup function."""
95 pass
96
97 def handle(self):
98 """Mock handle function."""
99 pass
100
101 def finish(self):
102 """Mock finish function."""
103 pass
104
105 def _set_headers(self):
106 """Mock getting the request headers."""
107 pass
108
109 def do_GET(self):
110 """Mock functionality for GET request."""
111 self._set_headers()
112 pass
113
114 def do_POST(self):
115 """Mock functionality for a POST request."""
116 self._set_headers()
117 self.notify_alarm(json.loads(post_data))
118
119 def notify_alarm(self, values):
120 """Mock the notify_alarm functionality to generate a valid response."""
121 config = Config.instance()
122 config.read_environ("aodh")
123 self._alarming = Alarming()
124 self._common = Common()
125 self._response = OpenStack_Response()
126 self._producer = KafkaProducer('alarm_response')
127 alarm_id = values['alarm_id']
128
129 auth_token = self._common._authenticate()
130 endpoint = self._common.get_endpoint("alarming")
131
132 # If authenticated generate and send response message
133 if (auth_token is not None and endpoint is not None):
134 url = "{}/v2/alarms/%s".format(endpoint) % alarm_id
135
136 # Get the resource_id of the triggered alarm and the date
137 result = self._common._perform_request(
138 url, auth_token, req_type="get")
139 alarm_details = json.loads(result.text)
140 gnocchi_rule = alarm_details['gnocchi_resources_threshold_rule']
141 resource_id = gnocchi_rule['resource_id']
142 a_date = "dd-mm-yyyy 00:00"
143
144 # Process an alarm notification if resource_id is valid
145 if resource_id is not None:
146 # Try generate and send response
147 try:
148 resp_message = self._response.generate_response(
149 'notify_alarm', a_id=alarm_id,
150 r_id=resource_id,
151 sev=values['severity'], date=a_date,
152 state=values['current'], vim_type="OpenStack")
153 self._producer.notify_alarm(
154 'notify_alarm', resp_message, 'alarm_response')
155 except Exception:
156 pass
157
158
159 class TestNotifier(unittest.TestCase):
160 """Test the NotifierHandler class for requests from aodh."""
161
162 def setUp(self):
163 """Setup tests."""
164 super(TestNotifier, self).setUp()
165 self.handler = NotifierHandler(
166 "mock_request", "mock_address", "mock_server")
167
168 @mock.patch.object(NotifierHandler, "_set_headers")
169 def test_do_GET(self, set_head):
170 """Test do_GET, generates headers for get request."""
171 self.handler.do_GET()
172
173 set_head.assert_called_once
174
175 @mock.patch.object(NotifierHandler, "notify_alarm")
176 @mock.patch.object(NotifierHandler, "_set_headers")
177 def test_do_POST(self, set_head, notify):
178 """Test do_POST functionality for a POST request."""
179 self.handler.do_POST()
180
181 set_head.assert_called_once
182 notify.assert_called_with(json.loads(post_data))
183
184 @mock.patch.object(Common, "get_endpoint")
185 @mock.patch.object(Common, "_authenticate")
186 @mock.patch.object(Common, "_perform_request")
187 def test_notify_alarm_unauth(self, perf_req, auth, endpoint):
188 """Test notify alarm when not authenticated with keystone."""
189 # Response request will not be performed unless there is a valid
190 # auth_token and endpoint
191 # Invalid auth_token and endpoint
192 auth.return_value = None
193 endpoint.return_value = None
194 self.handler.notify_alarm(json.loads(post_data))
195
196 perf_req.assert_not_called
197
198 # Valid endpoint
199 auth.return_value = None
200 endpoint.return_value = "my_endpoint"
201 self.handler.notify_alarm(json.loads(post_data))
202
203 perf_req.assert_not_called
204
205 # Valid auth_token
206 auth.return_value = "my_auth_token"
207 endpoint.return_value = None
208 self.handler.notify_alarm(json.loads(post_data))
209
210 perf_req.assert_not_called
211
212 @mock.patch.object(Common, "get_endpoint")
213 @mock.patch.object(OpenStack_Response, "generate_response")
214 @mock.patch.object(Common, "_authenticate")
215 @mock.patch.object(Common, "_perform_request")
216 def test_notify_alarm_invalid_alarm(self, perf_req, auth, resp, endpoint):
217 """Test valid authentication, invalid alarm details."""
218 # Mock valid auth_token and endpoint
219 auth.return_value = "my_auth_token"
220 endpoint.return_value = "my_endpoint"
221 perf_req.return_value = Response(invalid_get_resp)
222
223 self.handler.notify_alarm(json.loads(post_data))
224
225 # Response is not generated
226 resp.assert_not_called
227
228 @mock.patch.object(Common, "get_endpoint")
229 @mock.patch.object(OpenStack_Response, "generate_response")
230 @mock.patch.object(Common, "_authenticate")
231 @mock.patch.object(Common, "_perform_request")
232 def test_notify_alarm_resp_call(self, perf_req, auth, response, endpoint):
233 """Test notify_alarm tries to generate a response for SO."""
234 # Mock valid auth token and endpoint, valid response from aodh
235 auth.return_value = "my_auth_token"
236 endpoint.returm_value = "my_endpoint"
237 perf_req.return_value = Response(valid_get_resp)
238 self.handler.notify_alarm(json.loads(post_data))
239
240 response.assert_called_with('notify_alarm', a_id="my_alarm_id",
241 r_id="my_resource_id", sev="critical",
242 date="dd-mm-yyyy 00:00",
243 state="current_state",
244 vim_type="OpenStack")
245
246 @mock.patch.object(Common, "get_endpoint")
247 @mock.patch.object(KafkaProducer, "notify_alarm")
248 @mock.patch.object(OpenStack_Response, "generate_response")
249 @mock.patch.object(Common, "_authenticate")
250 @mock.patch.object(Common, "_perform_request")
251 def test_notify_alarm_invalid_resp(
252 self, perf_req, auth, response, notify, endpoint):
253 """Test the notify_alarm function, sends response to the producer."""
254 # Generate return values for valid notify_alarm operation
255 auth.return_value = "my_auth_token"
256 endpoint.return_value = "my_endpoint"
257 perf_req.return_value = Response(valid_get_resp)
258 response.return_value = invalid_notify_resp
259
260 self.handler.notify_alarm(json.loads(post_data))
261
262 notify.assert_not_called
263
264 @mock.patch.object(Common, "get_endpoint")
265 @mock.patch.object(KafkaProducer, "notify_alarm")
266 @mock.patch.object(OpenStack_Response, "generate_response")
267 @mock.patch.object(Common, "_authenticate")
268 @mock.patch.object(Common, "_perform_request")
269 def test_notify_alarm_valid_resp(
270 self, perf_req, auth, response, notify, endpoint):
271 """Test the notify_alarm function, sends response to the producer."""
272 # Generate return values for valid notify_alarm operation
273 auth.return_value = "my_auth_token"
274 endpoint.return_value = "my_endpoint"
275 perf_req.return_value = Response(valid_get_resp)
276 response.return_value = valid_notify_resp
277
278 self.handler.notify_alarm(json.loads(post_data))
279
280 notify.assert_called_with(
281 "notify_alarm", valid_notify_resp, "alarm_response")