diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-26 06:22:20 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-26 06:22:20 +0000 |
commit | 18bd2207b6c1977e99a93673a7be099e23f0f547 (patch) | |
tree | 40fd9e5913462a88be6ba24be6953383c5b39874 /ansible_collections/dellemc/openmanage/tests | |
parent | Releasing progress-linux version 10.0.1+dfsg-1~progress7.99u1. (diff) | |
download | ansible-18bd2207b6c1977e99a93673a7be099e23f0f547.tar.xz ansible-18bd2207b6c1977e99a93673a7be099e23f0f547.zip |
Merging upstream version 10.1.0+dfsg.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'ansible_collections/dellemc/openmanage/tests')
10 files changed, 512 insertions, 25 deletions
diff --git a/ansible_collections/dellemc/openmanage/tests/README.md b/ansible_collections/dellemc/openmanage/tests/README.md index a7d90ff01..e9bb0a645 100644 --- a/ansible_collections/dellemc/openmanage/tests/README.md +++ b/ansible_collections/dellemc/openmanage/tests/README.md @@ -1,6 +1,6 @@ ### Overview Dell OpenManage Ansible Modules unit test scripts are located under - [unit](./tests/unit) directory. + [unit](./unit) directory. ### Implementing the unit tests Any contribution must have an associated unit test. This section covers the diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_boot.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_boot.py index d5f43360f..bb746d12e 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_boot.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_boot.py @@ -347,7 +347,7 @@ class TestConfigBios(FakeAnsibleModule): result = self._run_module(idrac_default_args) assert 'msg' in result - def test_manin_success(self, boot_connection_mock, redfish_response_mock, idrac_default_args, mocker): + def test_main_success(self, boot_connection_mock, redfish_response_mock, idrac_default_args, mocker): idrac_default_args.update({"boot_source_override_mode": "legacy"}) redfish_response_mock.success = True mocker.patch(MODULE_PATH + 'idrac_boot.get_system_res_id', return_value=("System.Embedded.1", "")) @@ -403,4 +403,4 @@ class TestConfigBios(FakeAnsibleModule): job_resp.update({"JobState": "Running"}) # with pytest.raises(Exception) as err: module_return = self._run_module(idrac_default_args) - assert module_return["msg"] == "The boot settings job is triggered successfully." + assert module_return["msg"] == "The boot settings operation is triggered/submitted successfully." diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_certificates.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_certificates.py index 5e94faf91..4d45cae73 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_certificates.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_certificates.py @@ -288,6 +288,17 @@ class TestIdracCertificates(FakeAnsibleModule): assert "Permission denied" in ex.value.args[0] os.remove(temp_ssl.name) + def test_build_generate_csr_payload(self, idrac_default_args): + cert_params_data = { + "cert_params": { + "subject_alt_name": ['192.198.2.1,192.198.2.2', 'X.X.X.X'] + } + } + idrac_default_args.update(cert_params_data) + f_module = self.get_module_mock(params=idrac_default_args) + payload = self.module._build_generate_csr_payload(f_module, None) + assert payload["AlternativeNames"] == ['192.198.2.1,192.198.2.2,X.X.X.X'] + @pytest.mark.parametrize("params", [{"json_data": { "Actions": { EXPORT_SSL_CERTIFICATE: { diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_diagnostics.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_diagnostics.py index 987ff83d2..7a2cabf1f 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_diagnostics.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_diagnostics.py @@ -2,7 +2,7 @@ # # Dell OpenManage Ansible Modules -# Version 9.0.0 +# Version 9.3.0 # Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -1045,10 +1045,8 @@ class TestDiagnosticsType(FakeAnsibleModule): idrac_mock = mocker.MagicMock() diagnostics_mock = mocker.MagicMock() diagnostics_mock.execute.return_value = (None, None, None) - mocker.patch(MODULE_PATH + 'get_argument_spec', return_value={}) - mocker.patch(MODULE_PATH + 'idrac_auth_params', {}) - mocker.patch(MODULE_PATH + 'AnsibleModule', return_value=module_mock) + mocker.patch(MODULE_PATH + 'IdracAnsibleModule', return_value=module_mock) mocker.patch(MODULE_PATH + 'iDRACRedfishAPI', return_value=idrac_mock) mocker.patch(MODULE_PATH + 'DiagnosticsType.diagnostics_operation', return_value=diagnostics_mock) main() diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_license.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_license.py index a07cc1eb1..021de2fbb 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_license.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_license.py @@ -2,7 +2,7 @@ # # Dell OpenManage Ansible Modules -# Version 8.7.0 +# Version 9.3.0 # Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -281,21 +281,21 @@ class TestExportLicense(FakeAnsibleModule): 'license_id': 'test_license_id', 'share_parameters': { 'share_name': str(tmp_path), - 'file_name': 'test_lic' + 'file_name': 'test_lic.xml' } } idr_obj = MagicMock() - idr_obj.json_data = {"license_id": "1234", "LicenseFile": "test_license_content"} + idr_obj.json_data = {"license_id": "1234", "LicenseFile": "dGVzdF9saWNlbnNlX2NvbnRlbnQK"} mocker.patch(MODULE_PATH + API_INVOKE_MOCKER, return_value=idr_obj) idrac_default_args.update(export_params) f_module = self.get_module_mock(params=idrac_default_args, check_mode=False) export_license_obj = self.module.ExportLicense(idrac_connection_license_mock, f_module) result = export_license_obj._ExportLicense__export_license_local(EXPORT_URL_MOCK) - assert result.json_data == {'LicenseFile': 'test_license_content', 'license_id': '1234'} - assert os.path.exists(f"{tmp_path}/test_lic_iDRAC_license.txt") - if os.path.exists(f"{tmp_path}/test_lic_iDRAC_license.txt"): - os.remove(f"{tmp_path}/test_lic_iDRAC_license.txt") + assert result.json_data == {'LicenseFile': 'dGVzdF9saWNlbnNlX2NvbnRlbnQK', 'license_id': '1234'} + assert os.path.exists(f"{tmp_path}/test_lic.xml") + if os.path.exists(f"{tmp_path}/test_lic.xml"): + os.remove(f"{tmp_path}/test_lic.xml") export_params = { 'license_id': 'test_license_id', @@ -305,10 +305,10 @@ class TestExportLicense(FakeAnsibleModule): } idrac_default_args.update(export_params) result = export_license_obj._ExportLicense__export_license_local(EXPORT_URL_MOCK) - assert result.json_data == {'LicenseFile': 'test_license_content', 'license_id': '1234'} - assert os.path.exists(f"{tmp_path}/test_license_id_iDRAC_license.txt") - if os.path.exists(f"{tmp_path}/test_license_id_iDRAC_license.txt"): - os.remove(f"{tmp_path}/test_license_id_iDRAC_license.txt") + assert result.json_data == {'LicenseFile': 'dGVzdF9saWNlbnNlX2NvbnRlbnQK', 'license_id': '1234'} + assert os.path.exists(f"{tmp_path}/test_license_id_iDRAC_license.xml") + if os.path.exists(f"{tmp_path}/test_license_id_iDRAC_license.xml"): + os.remove(f"{tmp_path}/test_license_id_iDRAC_license.xml") def test_export_license_http(self, idrac_default_args, idrac_connection_license_mock, mocker): export_params = { @@ -736,8 +736,7 @@ class TestLicenseType(FakeAnsibleModule): # Mock the necessary functions and objects mocker.patch(MODULE_PATH + 'get_argument_spec', return_value={}) - mocker.patch(MODULE_PATH + 'idrac_auth_params', {}) - mocker.patch(MODULE_PATH + 'AnsibleModule', return_value=module_mock) + mocker.patch(MODULE_PATH + 'IdracAnsibleModule', return_value=module_mock) mocker.patch(MODULE_PATH + 'iDRACRedfishAPI', return_value=idrac_mock) mocker.patch(MODULE_PATH + 'get_idrac_firmware_version', return_value='3.1') mocker.patch(MODULE_PATH + 'LicenseType.license_operation', return_value=license_mock) diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_reset.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_reset.py index d8c23160e..8ff72383c 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_reset.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_reset.py @@ -57,6 +57,7 @@ STATUS_SUCCESS = [200, 202, 204] ERR_STATUS_CODE = [400, 404] RESET_KEY = "Oem.#DellManager.ResetToDefaults" RESTART_KEY = "#Manager.Reset" +SLEEP_KEY = "time.sleep" GET_BASE_URI_KEY = "Validation.get_base_uri" INVOKE_REQ_KEY = "iDRACRedfishAPI.invoke_request" GET_CUSTOM_DEFAULT_KEY = "CustomDefaultsDownloadURI" @@ -374,6 +375,7 @@ class TestFactoryReset(FakeAnsibleModule): return self.action_api_resp mocker.patch(MODULE_PATH + CHECK_IDRAC_VERSION, return_value=True) mocker.patch(MODULE_PATH + GET_BASE_URI_KEY, return_value=IDRAC_URI) + mocker.patch(MODULE_PATH + SLEEP_KEY, side_effect=lambda *args, **kwargs: None) mocker.patch(MODULE_PATH + INVOKE_REQ_KEY, return_value=obj) mocker.patch(MODULE_PATH + "get_dynamic_uri", side_effect=mock_get_dynamic_uri_request) @@ -397,6 +399,7 @@ class TestFactoryReset(FakeAnsibleModule): return self.action_api_resp mocker.patch(MODULE_PATH + "get_idrac_firmware_version", return_value="7.10.05") mocker.patch(MODULE_PATH + CHECK_IDRAC_VERSION, return_value=True) + mocker.patch(MODULE_PATH + SLEEP_KEY, side_effect=lambda *args, **kwargs: None) mocker.patch(MODULE_PATH + GET_BASE_URI_KEY, return_value=IDRAC_URI) mocker.patch(MODULE_PATH + INVOKE_REQ_KEY, side_effect=[obj, obj2, obj, URLError('URL error occurred'), obj, URLError('URL error occurred'), obj3, obj]) mocker.patch(MODULE_PATH + "get_dynamic_uri", @@ -422,6 +425,7 @@ class TestFactoryReset(FakeAnsibleModule): mocker.patch(MODULE_PATH + GET_BASE_URI_KEY, return_value=IDRAC_URI) mocker.patch(MODULE_PATH + VALIDATE_RESET_OPTION_KEY, side_effect=[(allowed_values, True), (allowed_values, True)]) mocker.patch(MODULE_PATH + INVOKE_REQ_KEY, side_effect=[obj, obj2, obj, obj2]) + mocker.patch(MODULE_PATH + SLEEP_KEY, side_effect=lambda *args, **kwargs: None) mocker.patch(MODULE_PATH + 'idrac_redfish_job_tracking', return_value=idrac_redfish_resp) mocker.patch(MODULE_PATH + "get_dynamic_uri", side_effect=[self.lc_status_api_links, self.action_api_resp_restart, @@ -499,6 +503,7 @@ class TestFactoryReset(FakeAnsibleModule): mocker.patch(MODULE_PATH + "get_idrac_firmware_version", return_value="7.10.05") mocker.patch(MODULE_PATH + CHECK_IDRAC_VERSION, return_value=True) mocker.patch(MODULE_PATH + CHECK_LC_STATUS, return_value=None) + mocker.patch(MODULE_PATH + SLEEP_KEY, side_effect=lambda *args, **kwargs: None) mocker.patch(MODULE_PATH + "Validation.validate_path", return_value=None) mocker.patch(MODULE_PATH + "Validation.validate_file_format", return_value=None) mocker.patch(MODULE_PATH + "Validation.validate_custom_option", return_value=None) @@ -534,6 +539,7 @@ class TestFactoryReset(FakeAnsibleModule): mocker.patch(MODULE_PATH + GET_BASE_URI_KEY, return_value=IDRAC_URI) mocker.patch(MODULE_PATH + VALIDATE_RESET_OPTION_KEY, return_value=(allowed_values, True)) mocker.patch(MODULE_PATH + INVOKE_REQ_KEY, side_effect=[obj]) + mocker.patch(MODULE_PATH + SLEEP_KEY, side_effect=lambda *args, **kwargs: None) mocker.patch(MODULE_PATH + "get_dynamic_uri", side_effect=mock_get_dynamic_uri_request) idrac_default_args.update({"reset_to_default": "ResetAllWithRootDefaults"}) diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_session.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_session.py index a28aab255..1cd10fc02 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_session.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_session.py @@ -2,7 +2,7 @@ # # Dell OpenManage Ansible Modules -# Version 9.2.0 +# Version 9.3.0 # Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -579,7 +579,7 @@ class TestMain(FakeAnsibleModule): StringIO(json_str))) else: ome_default_args.update({"state": "absent", "session_id": "1234", - "auth_token": "token123"}) + "x_auth_token": "token123"}) mocker.patch(MODULE_PATH + "DeleteSession.get_session_url", side_effect=exc_type('test')) result = self._run_module(ome_default_args) diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_storage_volume.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_storage_volume.py index 3cdf742d2..ad70fe701 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_storage_volume.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_idrac_storage_volume.py @@ -2,7 +2,7 @@ # # Dell OpenManage Ansible Modules -# Version 9.0.0 +# Version 9.3.0 # Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) @@ -39,6 +39,7 @@ ID_AND_LOCATION_BOTH_NOT_DEFINED = "Either id or location should be specified." DRIVES_NOT_DEFINED = "Drives must be defined for volume creation." NOT_ENOUGH_DRIVES = "Number of sufficient disks not found in Controller '{controller_id}'!" WAIT_TIMEOUT_MSG = "The job is not complete after {0} seconds." +TIME_TO_WAIT_MSG = "Time to wait value is invalid. Minimum value is 300 and Maximum is 3600 seconds." JOB_TRIGERRED = "Successfully triggered the {0} storage volume operation." VOLUME_NAME_REQUIRED_FOR_DELETE = "Virtual disk name is a required parameter for remove virtual disk operations." VOLUME_NOT_FOUND = "Unable to find the virtual disk." @@ -756,6 +757,27 @@ class TestStorageValidation(TestStorageBase): idr_obj = self.module.StorageValidation(idrac_connection_storage_volume_mock, f_module) idr_obj.validate_job_wait_negative_values() + def test_validate_time_to_wait(self, idrac_default_args, idrac_connection_storage_volume_mock, mocker): + # Scenario - when time_to_wait < 300 + mocker.patch(MODULE_PATH + ALL_STORAGE_DATA_METHOD, + return_value=TestStorageData.storage_data) + idrac_default_args.update({"time_to_wait": 299}) + f_module = self.get_module_mock( + params=idrac_default_args, check_mode=False) + idr_obj = self.module.StorageValidation(idrac_connection_storage_volume_mock, f_module) + with pytest.raises(Exception) as exc: + idr_obj.validate_time_to_wait() + assert exc.value.args[0] == TIME_TO_WAIT_MSG + + # Scenario - when time_to_wait > 3600 + idrac_default_args.update({"time_to_wait": 3601}) + f_module = self.get_module_mock( + params=idrac_default_args, check_mode=False) + idr_obj = self.module.StorageValidation(idrac_connection_storage_volume_mock, f_module) + with pytest.raises(Exception) as exc: + idr_obj.validate_time_to_wait() + assert exc.value.args[0] == TIME_TO_WAIT_MSG + @pytest.mark.parametrize("params", [ {"span_depth": -1, "span_length": 2, "capacity": 200, "strip_size": 131072}, {"span_depth": 1, "span_length": -1, "capacity": 200, "strip_size": 131072}, @@ -1058,6 +1080,7 @@ class TestStorageCreate(TestStorageBase): def test_validate_create(self, idrac_default_args, idrac_connection_storage_volume_mock, mocker): mocker.patch(MODULE_PATH + ALL_STORAGE_DATA_METHOD, return_value=TestStorageData.storage_data) + mocker.patch(MODULE_PATH + 'StorageValidation.validate_time_to_wait', return_value=None) mocker.patch(MODULE_PATH + 'StorageValidation.validate_controller_exists', return_value=None) mocker.patch(MODULE_PATH + 'StorageValidation.validate_job_wait_negative_values', return_value=None) mocker.patch(MODULE_PATH + 'StorageValidation.validate_negative_values_for_volume_params', return_value=None) diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_application_certificate.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_application_certificate.py index 99c49c210..a996a73ea 100644 --- a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_application_certificate.py +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_application_certificate.py @@ -107,7 +107,8 @@ class TestOmeAppCSR(FakeAnsibleModule): def test_generate_csr(self, mocker, ome_default_args, ome_connection_mock_for_application_certificate, ome_response_mock): - csr_json = {"CertificateData": "--BEGIN-REQUEST--"} + csr_data = "-----BEGIN CERTIFICATE REQUEST-----MIIFMDCCAxgCAQAwgbAxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhWaXJnaW5pYTES-----END CERTIFICATE REQUEST-----" + csr_json = {"CertificateData": csr_data} payload = {"DistinguishedName": "hostname.com", "DepartmentName": "Remote Access Group", "BusinessName": "Dell Inc.", "Locality": "Round Rock", "State": "Texas", "Country": "US", "Email": EMAIL_ADDRESS, "subject_alternative_names": "XX.XX.XX.XX"} @@ -121,4 +122,5 @@ class TestOmeAppCSR(FakeAnsibleModule): ome_response_mock.json_data = csr_json result = self.execute_module(ome_default_args) assert result['msg'] == "Successfully generated certificate signing request." - assert result['csr_status'] == {'CertificateData': '--BEGIN-REQUEST--'} + data = '''-----BEGIN CERTIFICATE REQUEST-----\nMIIFMDCCAxgCAQAwgbAxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhWaXJnaW5pYTES\n-----END CERTIFICATE REQUEST-----''' + assert result['csr_status']['CertificateData'] == data diff --git a/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_session.py b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_session.py new file mode 100644 index 000000000..6a547dc10 --- /dev/null +++ b/ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/test_ome_session.py @@ -0,0 +1,448 @@ +# -*- coding: utf-8 -*- + +# +# Dell OpenManage Ansible Modules +# Version 9.3.0 +# Copyright (C) 2024 Dell Inc. or its subsidiaries. All Rights Reserved. + +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# + +from __future__ import absolute_import, division, print_function + +from io import StringIO +import json + +from urllib.error import HTTPError, URLError +import pytest +from mock import MagicMock +from ansible_collections.dellemc.openmanage.plugins.modules import ome_session +from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import FakeAnsibleModule +from ansible.module_utils.urls import SSLValidationError +from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.common import AnsibleFailJSonException +from ansible.module_utils._text import to_text + +MODULE_PATH = 'ansible_collections.dellemc.openmanage.plugins.modules.ome_session.' +MODULE_UTILS_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.utils.' +SESSION_UTILS_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.session_utils.' + +REDFISH = "/redfish/v1" +SESSIONS = "Sessions" +ODATA = "@odata.id" +ODATA_REGEX = "(.*?)@odata" + +SESSION_URL = "/api/SessionService/Sessions" +GET_SESSION_URL = "Session.get_session_url" + +CREATE_SUCCESS_MSG = "The session has been created successfully." +DELETE_SUCCESS_MSG = "The session has been deleted successfully." +FAILURE_MSG = "Unable to '{operation}' a session." +CHANGES_FOUND_MSG = "Changes found to be applied." +NO_CHANGES_FOUND_MSG = "No changes found to be applied." +HTTPS_PATH = "https://testhost.com" +HTTP_ERROR = "http error message" +APPLICATION_JSON = "application/json" + + +class TestOMESession(FakeAnsibleModule): + """ + Main class for testing the ome_session module. + """ + module = ome_session + + @pytest.fixture + def ome_session_mock(self): + """ + Creates a mock object for the `ome_session` fixture. + + This function uses the `MagicMock` class from the `unittest.mock` module to create a mock + object. The mock object is then returned by the function. + + Returns: + MagicMock: A mock object representing the `ome_session`. + """ + ome_obj = MagicMock() + return ome_obj + + @pytest.fixture + def ome_connection_session_mock(self, mocker, ome_session_mock): + """ + Returns a mock object for the `SessionAPI` class from the `MODULE_PATH` module. + The mock object is initialized with the `ome_session_mock` as the return value. + The `__enter__` method of the mock object is also mocked to return `ome_session_mock`. + + :param mocker: The pytest fixture for mocking objects. + :type mocker: pytest_mock.plugin.MockerFixture + :param ome_session_mock: The mock object for the `ome_session_mock`. + :type ome_session_mock: Any + :return: The mock object for the `SessionAPI` class. + :rtype: MagicMock + """ + ome_conn_mock = mocker.patch(SESSION_UTILS_PATH + 'SessionAPI', return_value=ome_session_mock) + ome_conn_mock.return_value.__enter__.return_value = ome_session_mock + return ome_conn_mock + + def test_create_session_failure(self, ome_connection_session_mock, mocker): + """ + Test the failure scenario of creating a session. + + Args: + ome_connection_session_mock (MagicMock): A mock object for the + ome_connection_session. + mocker (MockerFixture): A fixture for mocking objects. + + Returns: + None + + This test function creates a session object using the `ome_connection_session_mock` and + `f_module` objects. + It sets the `f_module.check_mode` to False and `f_module.params` to a dictionary containing + the username and password. + It mocks the `ome_connection_session_mock.invoke_request` method to return a response + with a status code of 201. + It calls the `session_obj.execute()` method to create the session. + It asserts that the `f_module.exit_json` method is called once with the message "Unable to + 'create' a session." and `failed` set to True. + """ + f_module = MagicMock() + session_obj = self.module.OMESession(f_module) + f_module.check_mode = False + f_module.params = { + "username": "admin", + "password": "password" + } + response_mock = MagicMock() + response_mock.status_code = 400 + mocker.patch.object(ome_connection_session_mock.return_value, 'invoke_request', + return_value=response_mock) + session_obj.create_session() + f_module.exit_json.assert_called_once_with( + msg="Unable to 'create' a session.", + failed=True + ) + + def test_create_session_check_mode(self, ome_connection_session_mock): + """ + Test the create session functionality in check mode. + + Args: + ome_connection_session_mock (MagicMock): A mock object for the ome connection + session. + + Returns: + None + + This function tests the create session functionality in check mode. It creates an instance + of the `CreateSession` class with the provided `ome_connection_session_mock` and a mock + `f_module` object. + method of the `session_obj` to return the session URL. It also mocks the `exit_json` method + of the `f_module` object. + + Finally, it calls the `execute` method of the `session_obj` to execute the create session + functionality in check mode. + + Note: + This function assumes that the necessary imports and setup for the test are already + done. + """ + f_module = MagicMock() + session_obj = self.module.OMESession(f_module) + f_module = self.get_module_mock( + params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=True) + f_module.exit_json = MagicMock() + + session_obj.create_session() + + def test_create_session_success(self, ome_connection_session_mock): + """ + Test the successful creation of a session. + + Args: + ome_connection_session_mock (MagicMock): A mock object representing the ome + connection session. + + This test case verifies the successful creation of a session by mocking the necessary + objects and invoking the `execute()` method of the `CreateSession` class. It sets the + parameters for the `f_module` object, initializes the `session_obj` with the mocked + `ome_connection_session_mock` and `f_module`, and mocks the necessary methods and + attributes of the `ome` object. It then asserts that the `exit_json` method of the + `f_module` object is called with the expected arguments. + + Returns: + None + """ + f_module = self.get_module_mock( + params={"username": "admin", "password": "password"}, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.instance.invoke_request.return_value.status_code = 201 + session_obj.instance.invoke_request.return_value.json_data = {"SessionID": "123456"} + session_obj.instance.invoke_request.return_value.headers.get.return_value = "token123" + f_module.exit_json = MagicMock() + + session_obj.create_session() + f_module.exit_json.assert_called_once_with( + msg=CREATE_SUCCESS_MSG, + changed=True, + session_data={"SessionID": "123456"}, + x_auth_token="token123" + ) + + def test_delete_session_success_check_mode_changes(self, ome_connection_session_mock): + """ + Test the `delete_session_success_check_mode_changes` method of the `DeleteSession` class. + + This method is responsible for testing the success case when the `delete_session` method + is called in check mode. + It verifies that the `exit_json` method of the `f_module` object is called with the + appropriate arguments when the session is successfully deleted. + + Parameters: + - ome_connection_session_mock (MagicMock): A mock object representing the + `ome_connection_session` object. + + Returns: + None + """ + f_module = MagicMock() + session_obj = self.module.OMESession(f_module) + session_obj.get_session_status = MagicMock(return_value=True) + session_obj.delete_session() + f_module.exit_json.assert_called_once_with(msg=CHANGES_FOUND_MSG, changed=True) + + def test_delete_session_success_check_mode_no_changes(self, ome_connection_session_mock): + """ + Test the success case of deleting a session in check mode when no changes are expected. + + Args: + ome_connection_session_mock (MagicMock): A mock object representing the ome + connection session. + + This function tests the scenario where the deletion of a session is successful in check + mode and no changes are expected. It sets up the necessary mock objects and asserts that + the `exit_json` method of the `f_module` object is called once with the `msg` parameter + set to `NO_CHANGES_FOUND_MSG`. + + Returns: + None + """ + f_module = MagicMock() + session_obj = self.module.OMESession(f_module) + session_obj.instance.invoke_request.return_value.status_code = 201 + session_obj.delete_session() + f_module.exit_json.assert_called_once_with(msg=NO_CHANGES_FOUND_MSG) + + def test_delete_session_success(self, ome_connection_session_mock): + """ + Test the successful deletion of a session. + + This test function verifies the behavior of the `DeleteSession` class when a session is + successfully deleted. It mocks the `ome_connection_session_mock` object and sets up the + necessary parameters for the `f_module` object. It then creates an instance of the + `DeleteSession` class with the mocked `ome_connection_session_mock` and the + `f_module` object. + + The `invoke_request` method of the `ome` object of the `session_obj` is also mocked + to return a response with a status code of 200. The `exit_json` method of the `f_module` + object is mocked as well. + + The `execute` method of the `session_obj` is called to execute the deletion of the session. + Finally, the `exit_json` method of the `f_module` object is asserted to have been called + with the expected arguments, including the success message and the changed flag set to + `True`. + + Parameters: + - ome_connection_session_mock (MagicMock): A mocked object representing the + `ome_connection_session_mock` object. + + Returns: + None + """ + f_module = self.get_module_mock( + params={"session_id": "abcd", "hostname": "X.X.X.X", "x_auth_token": "token"}, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.get_session_status = MagicMock(return_value=200) + session_obj.instance.invoke_request.return_value.status_code = 204 + f_module.exit_json = MagicMock() + session_obj.delete_session() + f_module.exit_json.assert_called_once_with(msg=DELETE_SUCCESS_MSG, changed=True) + + def test_delete_session_success_02(self, ome_connection_session_mock): + """ + Test the successful deletion of a session. + + This test function verifies the behavior of the `DeleteSession` class when a session is + successfully deleted. It mocks the `ome_connection_session_mock` object and sets up the + necessary parameters for the `f_module` object. It then creates an instance of the + `DeleteSession` class with the mocked `ome_connection_session_mock` and the + `f_module` object. + + The `invoke_request` method of the `ome` object of the `session_obj` is also mocked + to return a response with a status code of 200. The `exit_json` method of the `f_module` + object is mocked as well. + + The `execute` method of the `session_obj` is called to execute the deletion of the session. + Finally, the `exit_json` method of the `f_module` object is asserted to have been called + with the expected arguments, including the success message and the changed flag set to + `True`. + + Parameters: + - ome_connection_session_mock (MagicMock): A mocked object representing the + `ome_connection_session_mock` object. + + Returns: + None + """ + f_module = self.get_module_mock( + params={"session_id": "abcd", "hostname": "X.X.X.X", "x_auth_token": "token"}, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.get_session_status = MagicMock(return_value=200) + session_obj.instance.invoke_request.return_value.status_code = 400 + obj = session_obj.delete_session() + assert not obj + + def test_delete_session_http_error(self, ome_connection_session_mock): + """ + Test the behavior of the `DeleteSession` class when an HTTP error occurs during the + deletion of a session. + + This test case creates a mock `f_module` object with the necessary parameters and + initializes a `DeleteSession` object with the mock `ome_connection_session_mock` and the + `f_module` object. It then sets up the necessary mock functions and side effects to + simulate an HTTP error during the deletion of a session. Finally, it executes the + `execute()` method of the `DeleteSession` object and asserts that an + `AnsibleFailJSonException` is raised with the expected failure message and error + information. + + Parameters: + - ome_connection_session_mock (MagicMock): A mock object representing the + `ome_connection_session_mock` parameter. + + Raises: + - AssertionError: If the expected failure message or error information is not present + in the raised exception. + + Returns: + None + """ + f_module = self.get_module_mock( + params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.get_session_status = MagicMock(return_value=200) + json_str = to_text(json.dumps({"data": "out"})) + session_obj.instance.invoke_request.side_effect = HTTPError(HTTPS_PATH, 200, + HTTP_ERROR, + {"accept-type": APPLICATION_JSON}, + StringIO(json_str)) + try: + session_obj.delete_session() + except AnsibleFailJSonException as ex: + assert ex.fail_msg == "Unable to 'delete' a session." + assert ex.fail_kwargs == {'error_info': {'data': 'out'}, 'failed': True} + + def test_delete_session_check_mode_false_no_changes(self, ome_connection_session_mock): + """ + Test the scenario where the delete session is executed in check mode with `check_mode` set + to False and no changes are expected. + + Args: + ome_connection_session_mock (MagicMock): A mock object representing the ome + connection session. + + Returns: + None + + This function creates a mock module object with the specified parameters and + initializes the `DeleteSession` object with the mock ome connection and module.It + sets the status code of the invoke request to 201. It then asserts that the `exit_json` + method of the module object is called once with the `msg` parameter set to the + `NO_CHANGES_FOUND_MSG` constant. + """ + f_module = self.get_module_mock( + params={"session_id": "abcd", "hostname": "X.X.X.X"}, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.instance.invoke_request.return_value.status_code = 201 + f_module.exit_json = MagicMock() + session_obj.delete_session() + f_module.exit_json.assert_called_once_with(msg=NO_CHANGES_FOUND_MSG) + + def test_get_session_status_http_error(self, ome_connection_session_mock): + """ + Test the behavior of the `DeleteSession` class when an HTTP error occurs during the + deletion of a session. + + This test case creates a mock `f_module` object with the necessary parameters and + initializes a `DeleteSession` object with the mock `ome_connection_session_mock` and the + `f_module` object. It then sets up the necessary mock functions and side effects to + simulate an HTTP error during the deletion of a session. Finally, it executes the + `execute()` method of the `DeleteSession` object and asserts that an + `AnsibleFailJSonException` is raised with the expected failure message and error + information. + + Parameters: + - ome_connection_session_mock (MagicMock): A mock object representing the + `ome_connection_session_mock` parameter. + + Raises: + - AssertionError: If the expected failure message or error information is not present + in the raised exception. + + Returns: + None + """ + params = {"session_id": "abcd", "hostname": "X.X.X.X"} + f_module = self.get_module_mock( + params=params, check_mode=False) + session_obj = self.module.OMESession(f_module) + session_obj.instance.invoke_request.side_effect = HTTPError(HTTPS_PATH, 400, '', {}, None) + with pytest.raises(HTTPError): + session_obj.get_session_status(SESSION_URL, params["session_id"]) + + @pytest.mark.parametrize("exc_type", + [URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError]) + def test_ome_session_main_exception_handling_case(self, exc_type, ome_default_args, mocker): + """ + Test the exception handling of the `ome_session_main` module. + + This function tests the exception handling of the `ome_session_main` module by mocking + different exceptions and verifying the expected behavior. + + Parameters: + - exc_type (Exception): The type of exception to be raised. + - ome_default_args (dict): The default arguments for the module. + - mocker (MockerFixture): The mocker fixture for mocking functions. + + Returns: + None + + Raises: + AssertionError: If the expected result does not match the actual result. + + Notes: + - The function uses the `pytest.mark.parametrize` decorator to parameterize the test + cases. + - The `exc_type` parameter represents the type of exception to be raised. + - The `ome_default_args` parameter contains the default arguments for the module. + - The `mocker` parameter is used to mock functions and simulate different exceptions. + - The function calls the `_run_module` method with the `ome_default_args` to execute + the module. + - The function verifies the expected result based on the raised exception type. + + """ + json_str = to_text(json.dumps({"data": "out"})) + if exc_type in [HTTPError, SSLValidationError]: + mocker.patch(MODULE_PATH + "OMESession.delete_session", + side_effect=exc_type(HTTPS_PATH, 400, + HTTP_ERROR, + {"accept-type": APPLICATION_JSON}, + StringIO(json_str))) + else: + ome_default_args.update({"state": "absent", "session_id": "abcd", + "x_auth_token": "token123"}) + mocker.patch(MODULE_PATH + "OMESession.delete_session", + side_effect=exc_type('test')) + result = self._run_module(ome_default_args) + if exc_type == URLError: + assert result['unreachable'] is True + else: + assert result['failed'] is True + assert 'msg' in result |