Debian Codegraph @

ansible_collections/dellemc/openmanage/tests/unit/plugins/module_utils/test_session_utils.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #
4 # Dell OpenManage Ansible Modules
5 # Version 9.2.0
6 # Copyright (C) 2024 Dell Inc.
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # All rights reserved. Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries.
10 # Other trademarks may be trademarks of their respective owners.
11 #
12
13 from __future__ import (absolute_import, division, print_function)
14
15 __metaclass__ = type
16
17 import os
18 import json
19 import pytest
20 from unittest.mock import MagicMock
21 from ansible.module_utils.urls import SSLValidationError
22 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
23 from ansible_collections.dellemc.openmanage.plugins.module_utils.session_utils import SessionAPI, OpenURLResponse
24
25 MODULE_UTIL_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.'
26 OPEN_URL = 'session_utils.open_url'
27 TEST_PATH = "/testpath"
28 INVOKE_REQUEST = 'session_utils.SessionAPI.invoke_request'
29 JOB_COMPLETE = 'session_utils.SessionAPI.wait_for_job_complete'
30 API_TASK = '/api/tasks'
31 SLEEP_TIME = 'session_utils.time.sleep'
32
33
34 class TestSessionRest(object):
35 """
36 Main class for testing the SessionUtils class.
37 """
38 @pytest.fixture
39 def mock_response(self):
40 """
41 Returns a MagicMock object representing a mock HTTP response.
42
43 The mock response has the following properties:
44 - `getcode()` method returns 200
45 - `headers` property is a dictionary containing the headers of the response
46 - `getheaders()` method returns the same dictionary as `headers`
47 - `read()` method returns a JSON string representing a dictionary with a "value" key and
48 "data" as its value
49
50 :return: A MagicMock object representing a mock HTTP response.
51 :rtype: MagicMock
52 """
53 mock_response = MagicMock()
54 mock_response.getcode.return_value = 200
55 mock_response.headers = mock_response.getheaders.return_value = {
56 'X-Auth-Token': 'token_id'}
57 mock_response.read.return_value = json.dumps({"value": "data"})
58 return mock_response
59
60 @pytest.fixture
61 def module_params(self):
62 """
63 Fixture that returns a dictionary containing module parameters.
64
65 :return: A dictionary with the following keys:
66 - 'hostname': The hostname of the module.
67 - 'username': The username for authentication.
68 - 'password': The password for authentication.
69 - 'port': The port number for the module.
70 """
71 module_parameters = {'hostname': 'xxx.xxx.x.x', 'username': 'username',
72 'password': 'password', 'port': '443'}
73 return module_parameters
74
75 @pytest.fixture
76 def session_utils_object(self, module_params):
77 """
78 Creates a SessionAPI object using the provided `module_params` and returns it.
79
80 :param module_params: A dictionary containing the parameters for the SessionAPI object.
81 :type module_params: dict
82 :return: A SessionAPI object.
83 :rtype: SessionAPI
84 """
85 session_utils_obj = SessionAPI(module_params)
86 return session_utils_obj
87
88 def test_invoke_request_with_session(self, mock_response, mocker, module_params):
89 """
90 Test the invoke_request method of the SessionAPI class with a session.
91
92 Args:
93 mock_response (MagicMock): A mocked response object.
94 mocker (MockerFixture): A fixture for mocking objects.
95 module_params (dict): The parameters for the module.
96
97 Returns:
98 None
99
100 Assertions:
101 - Asserts that the response status code is 200.
102 - Asserts that the response JSON data is {"value": "data"}.
103 - Asserts that the response success attribute is True.
104 """
105 mocker.patch(MODULE_UTIL_PATH + OPEN_URL,
106 return_value=mock_response)
107 obj = SessionAPI(module_params)
108 response = obj.invoke_request(TEST_PATH, "GET")
109 assert response.status_code == 200
110 assert response.json_data == {"value": "data"}
111 assert response.success is True
112
113 def test_invoke_request_without_session(self, mock_response, mocker):
114 """
115 Test the `invoke_request` method of the `SessionAPI` class without using a session.
116
117 This test case mocks the `open_url` function from the `MODULE_UTIL_PATH` module to return a
118 mock response.
119 It then creates an instance of the `SessionAPI` class with mock module parameters.
120 The `invoke_request` method is called with a test path and a GET method.
121 The test asserts that the response status code is 200, the response JSON data is
122 {"value": "data"},
123 and the response success flag is True.
124
125 Parameters:
126 - mock_response (MagicMock): A mock response object to be returned by the `open_url`
127 function.
128 - mocker (MockerFixture): A fixture provided by the pytest library for mocking
129 functions.
130
131 Returns:
132 None
133 """
134 mocker.patch(MODULE_UTIL_PATH + OPEN_URL,
135 return_value=mock_response)
136 module_params = {'hostname': 'XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX', 'username':
137 'username',
138 'password': 'password', "port": '443'}
139 obj = SessionAPI(module_params)
140 response = obj.invoke_request(TEST_PATH, "GET")
141 assert response.status_code == 200
142 assert response.json_data == {"value": "data"}
143 assert response.success is True
144
145 def test_invoke_request_without_session_with_header(self, mock_response, mocker,
146 module_params):
147 """
148 Test the `invoke_request` method of the `SessionAPI` class when a session is not used and a
149 header is provided.
150
151 This test method mocks the `open_url` function from the `module_utils` module to return a
152 mock response object. It then creates an instance of the `SessionAPI` class with the
153 provided `module_params`. The `invoke_request` method is called with a test path, a request
154 method of "POST", and a headers dictionary containing a single key-value pair.
155
156 The test asserts that the response status code is 200, the response JSON data is
157 `{"value": "data"}`, and the response success flag is `True`.
158
159 Parameters:
160 - `mock_response` (MagicMock): A mock response object to be returned by the `open_url`
161 function.
162 - `mocker` (MockerFixture): A fixture for patching and mocking objects.
163 - `module_params` (dict): A dictionary containing the module parameters.
164
165 Returns:
166 None
167 """
168 mocker.patch(MODULE_UTIL_PATH + OPEN_URL,
169 return_value=mock_response)
170 obj = SessionAPI(module_params)
171 response = obj.invoke_request(TEST_PATH, "POST", headers={"application": "octstream"})
172 assert response.status_code == 200
173 assert response.json_data == {"value": "data"}
174 assert response.success is True
175
176 @pytest.mark.parametrize("exc", [URLError, SSLValidationError, ConnectionError])
177 def test_invoke_request_error_case_handling(self, exc, mocker, module_params):
178 """
179 Test the error handling in the `invoke_request` method of the `SessionAPI` class.
180
181 This function tests the handling of different types of exceptions that can occur during an
182 HTTP request. It uses the `pytest.mark.parametrize` decorator to run the test multiple
183 times with different exception types. The test mocks the `open_url` method of the
184 `SessionAPI` class to raise the specified exception. It then asserts that the correct
185 exception is raised when calling the `invoke_request` method.
186
187 Args:
188 exc (Exception): The exception type to test.
189 mocker (MockerFixture): The mocker fixture used for mocking dependencies.
190 module_params (dict): The parameters for the `SessionAPI` object.
191
192 Raises:
193 exc: The specified exception type if it is raised during the `invoke_request` call.
194 """
195 mocker.patch(MODULE_UTIL_PATH + OPEN_URL,
196 side_effect=exc("test"))
197 with pytest.raises(exc):
198 obj = SessionAPI(module_params)
199 obj.invoke_request(TEST_PATH, "GET")
200
201 def test_invoke_request_http_error_handling(self, mock_response, mocker, module_params):
202 """
203 Test the HTTP error handling in the `invoke_request` method of the `SessionAPI` class.
204
205 Args:
206 mock_response (Mock): A mock object representing the response from the HTTP request.
207 mocker (MockerFixture): A fixture for mocking objects.
208 module_params (dict): The parameters for the module.
209
210 Raises:
211 HTTPError: If an HTTP error occurs during the invocation of the request.
212
213 Returns:
214 None
215 """
216 open_url_mock = mocker.patch(MODULE_UTIL_PATH + OPEN_URL,
217 return_value=mock_response)
218 open_url_mock.side_effect = HTTPError('https://testhost.com/', 400,
219 'Bad Request Error', {}, None)
220 with pytest.raises(HTTPError):
221 obj = SessionAPI(module_params)
222 obj.invoke_request(TEST_PATH, "GET")
223
224 @pytest.mark.parametrize("query_params", [
225 {"inp": {"$filter": "UserName eq 'admin'"},
226 "out": "%24filter=UserName+eq+%27admin%27"},
227 {"inp": {"$top": 1, "$skip": 2, "$filter": "JobType/Id eq 8"}, "out":
228 "%24top=1&%24skip=2&%24filter=JobType%2FId+eq+8"},
229 {"inp": {"$top": 1, "$skip": 3}, "out": "%24top=1&%24skip=3"}
230 ])
231 def test_build_url(self, query_params, mocker, session_utils_object):
232 """
233 builds complete url
234 """
235 base_uri = 'https://xxx.xxx.x.x:443/api'
236 path = "/AccountService/Accounts"
237 mocker.patch(MODULE_UTIL_PATH + 'session_utils.SessionAPI._get_url',
238 return_value=base_uri + path)
239 inp = query_params["inp"]
240 out = query_params["out"]
241 url = session_utils_object._build_url(
242 path, query_param=inp)
243 assert url == base_uri + path + "?" + out
244
245 def test_build_url_none(self, mocker, session_utils_object):
246 """
247 builds complete url
248 """
249 base_uri = 'https://xxx.xxx.x.x:443/api'
250 mocker.patch(MODULE_UTIL_PATH + 'redfish.Redfish._get_base_url',
251 return_value=base_uri)
252 url = session_utils_object._build_url("", None)
253 assert url == ""
254
255 def test_invalid_json_openurlresp(self):
256 """
257 Test the behavior when an invalid JSON string is passed to the `OpenURLResponse` object.
258
259 This test case creates an instance of the `OpenURLResponse` class with an empty dictionary
260 as the initial data.
261 Then, it sets the `body` attribute of the object to an invalid JSON string.
262 Finally, it asserts that calling the `json_data` attribute raises a `ValueError` with the
263 message "Unable to parse json".
264
265 Parameters:
266 self (TestCase): The current test case instance.
267
268 Returns:
269 None
270 """
271 obj = OpenURLResponse({})
272 obj.body = 'invalid json'
273 with pytest.raises(ValueError) as e:
274 obj.json_data
275 assert e.value.args[0] == "Unable to parse json"
276
277 def test_reason(self):
278 """
279 Test the `reason` property of the `OpenURLResponse` class.
280
281 This test case mocks the `read` method of the `obj` object to return an empty JSON string.
282 It then creates an instance of the `OpenURLResponse` class with the mocked `obj` object.
283 The `reason` property of the `OpenURLResponse` instance is then accessed and stored in the
284 `reason_ret` variable. Finally, the test asserts that the value of `reason_ret` is equal to
285 the expected value of "returning reason".
286
287 Parameters:
288 self (TestCase): The test case object.
289
290 Returns:
291 None
292 """
293 def mock_read():
294 return "{}"
295 obj = MagicMock()
296 obj.reason = "returning reason"
297 obj.read = mock_read
298 ourl = OpenURLResponse(obj)
299 reason_ret = ourl.reason
300 assert reason_ret == "returning reason"
301
302 def test_requests_ca_bundle_set(self, mocker, mock_response, session_utils_object):
303 """
304 Test if the `REQUESTS_CA_BUNDLE` environment variable is set correctly.
305
306 This function tests if the `REQUESTS_CA_BUNDLE` environment variable is set to the expected
307 value. It does this by setting the environment variable to a specific path, patching the
308 `invoke_request` method of the `session_utils_object` to return a mock response, and then
309 calling the `_get_omam_ca_env` method of the `session_utils_object`. Finally, it asserts
310 that the result of the `_get_omam_ca_env` method is equal to the expected path.
311
312 Parameters:
313 - mocker (MockerFixture): A fixture provided by the pytest library used to patch the
314 `invoke_request` method.
315 - mock_response (Mock): A mock object representing the response returned by the
316 `invoke_request` method.
317 - session_utils_object (SessionUtils): An instance of the `SessionUtils` class.
318
319 Returns:
320 None
321 """
322 os.environ["REQUESTS_CA_BUNDLE"] = "/path/to/requests_ca_bundle.pem"
323 mocker.patch(MODULE_UTIL_PATH + INVOKE_REQUEST,
324 return_value=mock_response)
325 result = session_utils_object._get_omam_ca_env()
326 assert result == "/path/to/requests_ca_bundle.pem"
327 del os.environ["REQUESTS_CA_BUNDLE"]
328
329 def test_curl_ca_bundle_set(self, mocker, mock_response, session_utils_object):
330 """
331 Test the functionality of the `curl_ca_bundle_set` method.
332
333 This test case verifies that the `curl_ca_bundle_set` method correctly sets the
334 `CURL_CA_BUNDLE` environment variable and retrieves the value using the `_get_omam_ca_env`
335 method.
336
337 Parameters:
338 - mocker (MockerFixture): A fixture provided by the pytest-mock library used to patch
339 the `invoke_request` method.
340 - mock_response (MagicMock): A mock object representing the response returned by the
341 `invoke_request` method.
342 - session_utils_object (SessionUtils): An instance of the `SessionUtils` class.
343
344 Returns:
345 None
346
347 Raises:
348 AssertionError: If the retrieved value from `_get_omam_ca_env` does not match the
349 expected value.
350
351 Note:
352 - The test case sets the `CURL_CA_BUNDLE` environment variable to
353 "/path/to/curl_ca_bundle.pem" before executing the test.
354 - The test case deletes the `CURL_CA_BUNDLE` environment variable after the test is
355 completed.
356 """
357 os.environ["CURL_CA_BUNDLE"] = "/path/to/curl_ca_bundle.pem"
358 mocker.patch(MODULE_UTIL_PATH + INVOKE_REQUEST,
359 return_value=mock_response)
360 result = session_utils_object._get_omam_ca_env()
361 assert result == "/path/to/curl_ca_bundle.pem"
362 del os.environ["CURL_CA_BUNDLE"]
363
364 def test_omam_ca_bundle_set(self, mocker, mock_response, session_utils_object):
365 """
366 Test the functionality of the `_get_omam_ca_env` method in the `SessionUtils` class.
367
368 This test case verifies that the `_get_omam_ca_env` method correctly retrieves the value of
369 the `OMAM_CA_BUNDLE` environment variable and returns it.
370
371 Parameters:
372 - mocker (MockerFixture): A fixture provided by the pytest library used for mocking
373 objects.
374 - mock_response (MagicMock): A mock object representing the response returned by the
375 `invoke_request` method.
376 - session_utils_object (SessionUtils): An instance of the `SessionUtils` class.
377
378 Returns:
379 None
380
381 Raises:
382 AssertionError: If the returned value from `_get_omam_ca_env` does not match the
383 expected value.
384
385 Side Effects:
386 - Sets the value of the `OMAM_CA_BUNDLE` environment variable to
387 "/path/to/omam_ca_bundle.pem".
388 - Deletes the `OMAM_CA_BUNDLE` environment variable after the test case is complete.
389 """
390 os.environ["OMAM_CA_BUNDLE"] = "/path/to/omam_ca_bundle.pem"
391 mocker.patch(MODULE_UTIL_PATH + INVOKE_REQUEST,
392 return_value=mock_response)
393 result = session_utils_object._get_omam_ca_env()
394 assert result == "/path/to/omam_ca_bundle.pem"
395 del os.environ["OMAM_CA_BUNDLE"]
396
397 def test_no_env_variable_set(self, mocker, mock_response, session_utils_object):
398 """
399 Test the case when no environment variable is set.
400
401 Args:
402 mocker (MockerFixture): The mocker fixture used to mock functions and objects.
403 mock_response (MagicMock): The mock response object used to simulate API responses.
404 session_utils_object (SessionUtils): The SessionUtils object under test.
405
406 Returns:
407 None
408
409 Asserts:
410 - The result of the _get_omam_ca_env() method is None.
411 """
412 mocker.patch(MODULE_UTIL_PATH + INVOKE_REQUEST,
413 return_value=mock_response)
414 result = session_utils_object._get_omam_ca_env()
415 assert result is None