Debian Codegraph @

ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_session.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #
4 # Dell OpenManage Ansible Modules
5 # Version 9.3.0
6 # Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved.
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 #
10
11 from __future__ import absolute_import, division, print_function
12
13 from io import StringIO
14 import json
15
16 from urllib.error import HTTPError, URLError
17 import pytest
18 from unittest.mock import MagicMock
19 from ansible_collections.dellemc.openmanage.plugins.modules import ome_session
20 from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import FakeAnsibleModule
21 from ansible.module_utils.urls import SSLValidationError
22 from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import AnsibleFailJSonException
23 from ansible.module_utils._text import to_text
24
25 MODULE_PATH = 'ansible_collections.dellemc.openmanage.plugins.modules.ome_session.'
26 MODULE_UTILS_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.utils.'
27 SESSION_UTILS_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.session_utils.'
28
29 REDFISH = "/redfish/v1"
30 SESSIONS = "Sessions"
31 ODATA = "@odata.id"
32 ODATA_REGEX = "(.*?)@odata"
33
34 SESSION_URL = "/api/SessionService/Sessions"
35 GET_SESSION_URL = "Session.get_session_url"
36
37 CREATE_SUCCESS_MSG = "The session has been created successfully."
38 DELETE_SUCCESS_MSG = "The session has been deleted successfully."
39 FAILURE_MSG = "Unable to '{operation}' a session."
40 CHANGES_FOUND_MSG = "Changes found to be applied."
41 NO_CHANGES_FOUND_MSG = "No changes found to be applied."
42 HTTPS_PATH = "https://testhost.com"
43 HTTP_ERROR = "http error message"
44 APPLICATION_JSON = "application/json"
45
46
47 class TestOMESession(FakeAnsibleModule):
48 """
49 Main class for testing the ome_session module.
50 """
51 module = ome_session
52
53 @pytest.fixture
54 def ome_session_mock(self):
55 """
56 Creates a mock object for the `ome_session` fixture.
57
58 This function uses the `MagicMock` class from the `unittest.mock` module to create a mock
59 object. The mock object is then returned by the function.
60
61 Returns:
62 MagicMock: A mock object representing the `ome_session`.
63 """
64 ome_obj = MagicMock()
65 return ome_obj
66
67 @pytest.fixture
68 def ome_connection_session_mock(self, mocker, ome_session_mock):
69 """
70 Returns a mock object for the `SessionAPI` class from the `MODULE_PATH` module.
71 The mock object is initialized with the `ome_session_mock` as the return value.
72 The `__enter__` method of the mock object is also mocked to return `ome_session_mock`.
73
74 :param mocker: The pytest fixture for mocking objects.
75 :type mocker: pytest_mock.plugin.MockerFixture
76 :param ome_session_mock: The mock object for the `ome_session_mock`.
77 :type ome_session_mock: Any
78 :return: The mock object for the `SessionAPI` class.
79 :rtype: MagicMock
80 """
81 ome_conn_mock = mocker.patch(SESSION_UTILS_PATH + 'SessionAPI', return_value=ome_session_mock)
82 ome_conn_mock.return_value.__enter__.return_value = ome_session_mock
83 return ome_conn_mock
84
85 def test_create_session_failure(self, ome_connection_session_mock, mocker):
86 """
87 Test the failure scenario of creating a session.
88
89 Args:
90 ome_connection_session_mock (MagicMock): A mock object for the
91 ome_connection_session.
92 mocker (MockerFixture): A fixture for mocking objects.
93
94 Returns:
95 None
96
97 This test function creates a session object using the `ome_connection_session_mock` and
98 `f_module` objects.
99 It sets the `f_module.check_mode` to False and `f_module.params` to a dictionary containing
100 the username and password.
101 It mocks the `ome_connection_session_mock.invoke_request` method to return a response
102 with a status code of 201.
103 It calls the `session_obj.execute()` method to create the session.
104 It asserts that the `f_module.exit_json` method is called once with the message "Unable to
105 'create' a session." and `failed` set to True.
106 """
107 f_module = MagicMock()
108 session_obj = self.module.OMESession(f_module)
109 f_module.check_mode = False
110 f_module.params = {
111 "username": "admin",
112 "password": "password"
113 }
114 response_mock = MagicMock()
115 response_mock.status_code = 400
116 mocker.patch.object(ome_connection_session_mock.return_value, 'invoke_request',
117 return_value=response_mock)
118 session_obj.create_session()
119 f_module.exit_json.assert_called_once_with(
120 msg="Unable to 'create' a session.",
121 failed=True
122 )
123
124 def test_create_session_check_mode(self, ome_connection_session_mock):
125 """
126 Test the create session functionality in check mode.
127
128 Args:
129 ome_connection_session_mock (MagicMock): A mock object for the ome connection
130 session.
131
132 Returns:
133 None
134
135 This function tests the create session functionality in check mode. It creates an instance
136 of the `CreateSession` class with the provided `ome_connection_session_mock` and a mock
137 `f_module` object.
138 method of the `session_obj` to return the session URL. It also mocks the `exit_json` method
139 of the `f_module` object.
140
141 Finally, it calls the `execute` method of the `session_obj` to execute the create session
142 functionality in check mode.
143
144 Note:
145 This function assumes that the necessary imports and setup for the test are already
146 done.
147 """
148 f_module = MagicMock()
149 session_obj = self.module.OMESession(f_module)
150 f_module = self.get_module_mock(
151 params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=True)
152 f_module.exit_json = MagicMock()
153
154 session_obj.create_session()
155
156 def test_create_session_success(self, ome_connection_session_mock):
157 """
158 Test the successful creation of a session.
159
160 Args:
161 ome_connection_session_mock (MagicMock): A mock object representing the ome
162 connection session.
163
164 This test case verifies the successful creation of a session by mocking the necessary
165 objects and invoking the `execute()` method of the `CreateSession` class. It sets the
166 parameters for the `f_module` object, initializes the `session_obj` with the mocked
167 `ome_connection_session_mock` and `f_module`, and mocks the necessary methods and
168 attributes of the `ome` object. It then asserts that the `exit_json` method of the
169 `f_module` object is called with the expected arguments.
170
171 Returns:
172 None
173 """
174 f_module = self.get_module_mock(
175 params={"username": "admin", "password": "password"}, check_mode=False)
176 session_obj = self.module.OMESession(f_module)
177 session_obj.instance.invoke_request.return_value.status_code = 201
178 session_obj.instance.invoke_request.return_value.json_data = {"SessionID": "123456"}
179 session_obj.instance.invoke_request.return_value.headers.get.return_value = "token123"
180 f_module.exit_json = MagicMock()
181
182 session_obj.create_session()
183 f_module.exit_json.assert_called_once_with(
184 msg=CREATE_SUCCESS_MSG,
185 changed=True,
186 session_data={"SessionID": "123456"},
187 x_auth_token="token123"
188 )
189
190 def test_delete_session_success_check_mode_changes(self, ome_connection_session_mock):
191 """
192 Test the `delete_session_success_check_mode_changes` method of the `DeleteSession` class.
193
194 This method is responsible for testing the success case when the `delete_session` method
195 is called in check mode.
196 It verifies that the `exit_json` method of the `f_module` object is called with the
197 appropriate arguments when the session is successfully deleted.
198
199 Parameters:
200 - ome_connection_session_mock (MagicMock): A mock object representing the
201 `ome_connection_session` object.
202
203 Returns:
204 None
205 """
206 f_module = MagicMock()
207 session_obj = self.module.OMESession(f_module)
208 session_obj.get_session_status = MagicMock(return_value=True)
209 session_obj.delete_session()
210 f_module.exit_json.assert_called_once_with(msg=CHANGES_FOUND_MSG, changed=True)
211
212 def test_delete_session_success_check_mode_no_changes(self, ome_connection_session_mock):
213 """
214 Test the success case of deleting a session in check mode when no changes are expected.
215
216 Args:
217 ome_connection_session_mock (MagicMock): A mock object representing the ome
218 connection session.
219
220 This function tests the scenario where the deletion of a session is successful in check
221 mode and no changes are expected. It sets up the necessary mock objects and asserts that
222 the `exit_json` method of the `f_module` object is called once with the `msg` parameter
223 set to `NO_CHANGES_FOUND_MSG`.
224
225 Returns:
226 None
227 """
228 f_module = MagicMock()
229 session_obj = self.module.OMESession(f_module)
230 session_obj.instance.invoke_request.return_value.status_code = 201
231 session_obj.delete_session()
232 f_module.exit_json.assert_called_once_with(msg=NO_CHANGES_FOUND_MSG)
233
234 def test_delete_session_success(self, ome_connection_session_mock):
235 """
236 Test the successful deletion of a session.
237
238 This test function verifies the behavior of the `DeleteSession` class when a session is
239 successfully deleted. It mocks the `ome_connection_session_mock` object and sets up the
240 necessary parameters for the `f_module` object. It then creates an instance of the
241 `DeleteSession` class with the mocked `ome_connection_session_mock` and the
242 `f_module` object.
243
244 The `invoke_request` method of the `ome` object of the `session_obj` is also mocked
245 to return a response with a status code of 200. The `exit_json` method of the `f_module`
246 object is mocked as well.
247
248 The `execute` method of the `session_obj` is called to execute the deletion of the session.
249 Finally, the `exit_json` method of the `f_module` object is asserted to have been called
250 with the expected arguments, including the success message and the changed flag set to
251 `True`.
252
253 Parameters:
254 - ome_connection_session_mock (MagicMock): A mocked object representing the
255 `ome_connection_session_mock` object.
256
257 Returns:
258 None
259 """
260 f_module = self.get_module_mock(
261 params={"session_id": "abcd", "hostname": "X.X.X.X", "x_auth_token": "token"}, check_mode=False)
262 session_obj = self.module.OMESession(f_module)
263 session_obj.get_session_status = MagicMock(return_value=200)
264 session_obj.instance.invoke_request.return_value.status_code = 204
265 f_module.exit_json = MagicMock()
266 session_obj.delete_session()
267 f_module.exit_json.assert_called_once_with(msg=DELETE_SUCCESS_MSG, changed=True)
268
269 def test_delete_session_success_02(self, ome_connection_session_mock):
270 """
271 Test the successful deletion of a session.
272
273 This test function verifies the behavior of the `DeleteSession` class when a session is
274 successfully deleted. It mocks the `ome_connection_session_mock` object and sets up the
275 necessary parameters for the `f_module` object. It then creates an instance of the
276 `DeleteSession` class with the mocked `ome_connection_session_mock` and the
277 `f_module` object.
278
279 The `invoke_request` method of the `ome` object of the `session_obj` is also mocked
280 to return a response with a status code of 200. The `exit_json` method of the `f_module`
281 object is mocked as well.
282
283 The `execute` method of the `session_obj` is called to execute the deletion of the session.
284 Finally, the `exit_json` method of the `f_module` object is asserted to have been called
285 with the expected arguments, including the success message and the changed flag set to
286 `True`.
287
288 Parameters:
289 - ome_connection_session_mock (MagicMock): A mocked object representing the
290 `ome_connection_session_mock` object.
291
292 Returns:
293 None
294 """
295 f_module = self.get_module_mock(
296 params={"session_id": "abcd", "hostname": "X.X.X.X", "x_auth_token": "token"}, check_mode=False)
297 session_obj = self.module.OMESession(f_module)
298 session_obj.get_session_status = MagicMock(return_value=200)
299 session_obj.instance.invoke_request.return_value.status_code = 400
300 obj = session_obj.delete_session()
301 assert not obj
302
303 def test_delete_session_http_error(self, ome_connection_session_mock):
304 """
305 Test the behavior of the `DeleteSession` class when an HTTP error occurs during the
306 deletion of a session.
307
308 This test case creates a mock `f_module` object with the necessary parameters and
309 initializes a `DeleteSession` object with the mock `ome_connection_session_mock` and the
310 `f_module` object. It then sets up the necessary mock functions and side effects to
311 simulate an HTTP error during the deletion of a session. Finally, it executes the
312 `execute()` method of the `DeleteSession` object and asserts that an
313 `AnsibleFailJSonException` is raised with the expected failure message and error
314 information.
315
316 Parameters:
317 - ome_connection_session_mock (MagicMock): A mock object representing the
318 `ome_connection_session_mock` parameter.
319
320 Raises:
321 - AssertionError: If the expected failure message or error information is not present
322 in the raised exception.
323
324 Returns:
325 None
326 """
327 f_module = self.get_module_mock(
328 params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=False)
329 session_obj = self.module.OMESession(f_module)
330 session_obj.get_session_status = MagicMock(return_value=200)
331 json_str = to_text(json.dumps({"data": "out"}))
332 session_obj.instance.invoke_request.side_effect = HTTPError(HTTPS_PATH, 200,
333 HTTP_ERROR,
334 {"accept-type": APPLICATION_JSON},
335 StringIO(json_str))
336 try:
337 session_obj.delete_session()
338 except AnsibleFailJSonException as ex:
339 assert ex.fail_msg == "Unable to 'delete' a session."
340 assert ex.fail_kwargs == {'error_info': {'data': 'out'}, 'failed': True}
341
342 def test_delete_session_check_mode_false_no_changes(self, ome_connection_session_mock):
343 """
344 Test the scenario where the delete session is executed in check mode with `check_mode` set
345 to False and no changes are expected.
346
347 Args:
348 ome_connection_session_mock (MagicMock): A mock object representing the ome
349 connection session.
350
351 Returns:
352 None
353
354 This function creates a mock module object with the specified parameters and
355 initializes the `DeleteSession` object with the mock ome connection and module.It
356 sets the status code of the invoke request to 201. It then asserts that the `exit_json`
357 method of the module object is called once with the `msg` parameter set to the
358 `NO_CHANGES_FOUND_MSG` constant.
359 """
360 f_module = self.get_module_mock(
361 params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=False)
362 session_obj = self.module.OMESession(f_module)
363 session_obj.instance.invoke_request.return_value.status_code = 201
364 f_module.exit_json = MagicMock()
365 session_obj.delete_session()
366 f_module.exit_json.assert_called_once_with(msg=NO_CHANGES_FOUND_MSG)
367
368 def test_get_session_status_http_error(self, ome_connection_session_mock):
369 """
370 Test the behavior of the `DeleteSession` class when an HTTP error occurs during the
371 deletion of a session.
372
373 This test case creates a mock `f_module` object with the necessary parameters and
374 initializes a `DeleteSession` object with the mock `ome_connection_session_mock` and the
375 `f_module` object. It then sets up the necessary mock functions and side effects to
376 simulate an HTTP error during the deletion of a session. Finally, it executes the
377 `execute()` method of the `DeleteSession` object and asserts that an
378 `AnsibleFailJSonException` is raised with the expected failure message and error
379 information.
380
381 Parameters:
382 - ome_connection_session_mock (MagicMock): A mock object representing the
383 `ome_connection_session_mock` parameter.
384
385 Raises:
386 - AssertionError: If the expected failure message or error information is not present
387 in the raised exception.
388
389 Returns:
390 None
391 """
392 params = {"session_id": "abcd", "hostname": "X.X.X.X"}
393 f_module = self.get_module_mock(
394 params=params, check_mode=False)
395 session_obj = self.module.OMESession(f_module)
396 session_obj.instance.invoke_request.side_effect = HTTPError(HTTPS_PATH, 400, '', {}, None)
397 with pytest.raises(HTTPError):
398 session_obj.get_session_status(SESSION_URL, params["session_id"])
399
400 @pytest.mark.parametrize("exc_type",
401 [URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError])
402 def test_ome_session_main_exception_handling_case(self, exc_type, ome_default_args, mocker):
403 """
404 Test the exception handling of the `ome_session_main` module.
405
406 This function tests the exception handling of the `ome_session_main` module by mocking
407 different exceptions and verifying the expected behavior.
408
409 Parameters:
410 - exc_type (Exception): The type of exception to be raised.
411 - ome_default_args (dict): The default arguments for the module.
412 - mocker (MockerFixture): The mocker fixture for mocking functions.
413
414 Returns:
415 None
416
417 Raises:
418 AssertionError: If the expected result does not match the actual result.
419
420 Notes:
421 - The function uses the `pytest.mark.parametrize` decorator to parameterize the test
422 cases.
423 - The `exc_type` parameter represents the type of exception to be raised.
424 - The `ome_default_args` parameter contains the default arguments for the module.
425 - The `mocker` parameter is used to mock functions and simulate different exceptions.
426 - The function calls the `_run_module` method with the `ome_default_args` to execute
427 the module.
428 - The function verifies the expected result based on the raised exception type.
429
430 """
431 json_str = to_text(json.dumps({"data": "out"}))
432 if exc_type in [HTTPError, SSLValidationError]:
433 mocker.patch(MODULE_PATH + "OMESession.delete_session",
434 side_effect=exc_type(HTTPS_PATH, 400,
435 HTTP_ERROR,
436 {"accept-type": APPLICATION_JSON},
437 StringIO(json_str)))
438 else:
439 ome_default_args.update({"state": "absent", "session_id": "abcd",
440 "x_auth_token": "token123"})
441 mocker.patch(MODULE_PATH + "OMESession.delete_session",
442 side_effect=exc_type('test'))
443 result = self._run_module(ome_default_args)
444 if exc_type == URLError:
445 assert result['unreachable'] is True
446 else:
447 assert result['failed'] is True
448 assert 'msg' in result