def test_tweak_url_pass(self): """Verify a range of valid netapp eseries rest api urls pass.""" test_set = [ ("http://localhost/devmgr/v2", "http://localhost:8080/devmgr/v2/"), ("localhost", "https://localhost:8443/devmgr/v2/"), ("localhost:8443/devmgr/v2", "https://localhost:8443/devmgr/v2/"), ("https://localhost/devmgr/v2", "https://localhost:8443/devmgr/v2/"), ("http://localhost:8443", "https://localhost:8443/devmgr/v2/"), ("http://localhost:/devmgr/v2", "https://localhost:8443/devmgr/v2/"), ("http://localhost:8080", "http://localhost:8080/devmgr/v2/"), ("http://localhost", "http://localhost:8080/devmgr/v2/"), ("localhost/devmgr/v2", "https://localhost:8443/devmgr/v2/"), ("localhost/devmgr", "https://localhost:8443/devmgr/v2/"), ("localhost/devmgr/v3", "https://localhost:8443/devmgr/v2/"), ("localhost/something", "https://localhost:8443/devmgr/v2/"), ("ftp://localhost", "https://localhost:8443/devmgr/v2/"), ("ftp://localhost:8080", "http://localhost:8080/devmgr/v2/"), ("ftp://localhost/devmgr/v2/", "https://localhost:8443/devmgr/v2/") ] for test in test_set: self._set_args({"api_url": test[0]}) with mock.patch(self.REQ_FUNC, side_effect=[ URLError(""), (200, { "runningAsProxy": False }) ]): base = StubNetAppESeriesModule() base._tweak_url() self.assertTrue(base.url == test[1])
def test_url_error_handling(self, mocker): request = mocker.patch.object(client, "Request").return_value request.open.side_effect = URLError("bad error") c = client.Client("https://host", "u", "p", True, "ca") with pytest.raises(errors.UnitError, match="request failed"): c.request("get", ("config", "c"))
def test_request_raises_on_bad_url(self, open_url_mock): open_url_mock.side_effect = URLError('URL is invalid') client = ManifoldApiClient('token-123') with self.assertRaises(ApiError) as context: client.request('test', 'endpoint') self.assertEqual( 'Failed lookup url for https://api.test.manifold.co/v1/endpoint : <url' 'open error URL is invalid>', str(context.exception))
def test_fetch_storage_resource_error_case_05(self, redfish_connection_mock_for_storage_volume, redfish_response_mock): f_module = self.get_module_mock() msg = "connection error" redfish_connection_mock_for_storage_volume.root_uri = "/redfish/v1/" redfish_connection_mock_for_storage_volume.invoke_request.side_effect = URLError(msg) with pytest.raises(Exception, match=msg) as exc: self.module.fetch_storage_resource(f_module, redfish_connection_mock_for_storage_volume)
def test_url_error(self, mocker): request_mock = mocker.patch.object(client, "Request").return_value request_mock.open.side_effect = URLError("some error") c = client.Client("https://instance.com", "user", "pass") with pytest.raises(errors.ServiceNowError, match="some error"): c.request("GET", "api/now/some/path")
def test_url_error(self, mocker): auth_resp = mocker.Mock() auth_resp.read.return_value = '{"access_token": "token"}' open_url = mocker.patch.object(client, "open_url") open_url.side_effect = auth_resp, URLError("Invalid") with pytest.raises(errors.ClientError): client.Client("http://ex.com/", "user", "pass").get("/path")
def test_check_specified_identifier_exists_in_the_system_exception_case_03( self, redfish_connection_mock_for_storage_volume, redfish_response_mock): f_module = self.get_module_mock(params={"controller_id": "1234"}) redfish_connection_mock_for_storage_volume.invoke_request.side_effect = URLError( 'test') with pytest.raises(URLError) as exc: self.module.check_specified_identifier_exists_in_the_system( f_module, redfish_connection_mock_for_storage_volume, "uri", "Specified Controller 123 does not exist in the System.")
def test_is_embedded_fail(self): """Verify exception is thrown when a web service's rest api fails to return about information.""" self._set_args() with mock.patch(self.REQ_FUNC, return_value=Exception()): with self.assertRaisesRegexp( AnsibleFailJson, r"Failed to retrieve the webservices about information!"): base = StubNetAppESeriesModule() base.is_embedded() with mock.patch(self.REQ_FUNC, side_effect=[URLError(""), Exception()]): with self.assertRaisesRegexp( AnsibleFailJson, r"Failed to retrieve the webservices about information!"): base = StubNetAppESeriesModule() base.is_embedded()
def _configure_mock(self, mock, test_case): def config(): auth_response = '{"access_token": "token"}' if test_case['existing_object']: # In the case of testing update we return 'existing_object' from API payload = json.dumps(test_case['existing_object']) return { 'return_value.read.side_effect': [auth_response, payload, payload] } elif test_case['params'].get('state', 'present') == 'absent': # If the state is absent and 'existing_object' is not present, # we want empty response by default return {'return_value.read.side_effect': [auth_response, '{}']} return {'return_value.read.return_value': auth_response} if test_case['is_http_error']: mock.configure_mock(**{'side_effect': URLError('unreachable')}) else: mock.configure_mock(**config()) return mock
def test_ome_application_network_time_main_success_exception_case3( self, exc_type, mocker, ome_default_args, ome_connection_mock_for_application_network_time, ome_response_mock): mocker.patch( "ansible.modules.remote_management.dellemc.ome_application_network_time.validate_time_zone" ) ome_default_args.update({ "enable_ntp": False, "system_time": "2020-03-31 21:35:18" }) json_str = to_text(json.dumps({"info": "error_details"})) if exc_type == URLError: mocker.patch( 'ansible.modules.remote_management.dellemc.ome_application_network_time.get_payload', side_effect=URLError('TESTS')) result = self._run_module(ome_default_args) assert result["unreachable"] is True assert result['msg'] == '<urlopen error TESTS>' assert result['changed'] is False elif exc_type not in [HTTPError, SSLValidationError]: mocker.patch( 'ansible.modules.remote_management.dellemc.ome_application_network_time.get_payload', side_effect=exc_type("exception message")) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True else: mocker.patch( 'ansible.modules.remote_management.dellemc.ome_application_network_time.get_payload', side_effect=exc_type('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str))) result = self._run_module_with_fail_json(ome_default_args) assert result['failed'] is True assert 'time_configuration' not in result assert 'msg' in result
def test_url_error(self, mocker): open_url = mocker.patch.object(http, "open_url") open_url.side_effect = URLError("Invalid") with pytest.raises(errors.HttpError): http.request("GET", "example.com/bad")
class TestIdracRedfishStorageController(FakeAnsibleModule): module = idrac_redfish_storage_controller msg = "All of the following: key, key_id and old_key are required for ReKey operation." @pytest.mark.parametrize("input", [{"param": {"command": "ReKey", "mode": "LKM", "key_id": "myid"}, "msg": msg}, {"param": {"command": "ReKey", "mode": "LKM", "old_key": "mykey"}, "msg": msg}, {"param": {"command": "ReKey", "mode": "LKM", "key": "mykey"}, "msg": msg} ]) def test_validate_inputs_error_case_01(self, input): f_module = self.get_module_mock(params=input["param"]) with pytest.raises(Exception) as exc: self.module.validate_inputs(f_module) assert exc.value.args[0] == input["msg"] @pytest.mark.parametrize("input", [{"controller_id": "c1"}]) def test_check_encryption_capability_failure(self, idrac_connection_mock_for_redfish_storage_controller, redfish_response_mock, input): f_module = self.get_module_mock(params=input) msg = "Encryption is not supported on the storage controller: c1" redfish_response_mock.success = True redfish_response_mock.json_data = {'Oem':{'Dell':{'DellController':{'SecurityStatus':"EncryptionNotCapable"}}}} with pytest.raises(Exception) as exc: self.module.check_encryption_capability(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == msg def test_check_raid_service(self, idrac_connection_mock_for_redfish_storage_controller, redfish_response_mock): f_module = self.get_module_mock() msg = "Installed version of iDRAC does not support this feature using Redfish API" redfish_response_mock.success = False with pytest.raises(Exception) as exc: self.module.check_raid_service(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == msg @pytest.mark.parametrize("input", [ {"error": URLError("test"), "msg": "<urlopen error test>"} ]) def test_check_raid_service_exceptions(self, idrac_connection_mock_for_redfish_storage_controller, input): f_module = self.get_module_mock(params=input) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = input["error"] with pytest.raises(Exception) as exc: self.module.check_raid_service(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == input['msg'] def test_check_raid_service_HttpError_exception(self, idrac_connection_mock_for_redfish_storage_controller, redfish_default_args): f_module = self.get_module_mock(params=redfish_default_args) json_str = to_text(json.dumps({"data": "out"})) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = HTTPError('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str)) with pytest.raises(Exception) as exc: self.module.check_raid_service(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == "Installed version of iDRAC does not support this feature using Redfish API" @pytest.mark.parametrize("input", [{"volume_id": ["v1"]}]) def test_check_volume_array_exists(self, idrac_connection_mock_for_redfish_storage_controller, redfish_response_mock, input): f_module = self.get_module_mock(params=input) msg = "Unable to locate the virtual disk with the ID: v1" redfish_response_mock.success = False with pytest.raises(Exception) as exc: self.module.check_volume_array_exists(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == msg def test_check_volume_array_exists_HttpError_exceptions(self, redfish_response_mock, redfish_default_args, idrac_connection_mock_for_redfish_storage_controller): redfish_default_args.update({"volume_id": ["v1"]}) redfish_response_mock.json_data = {"volume_id": ["v1"]} f_module = self.get_module_mock(params=redfish_default_args) json_str = to_text(json.dumps({"data": "out"})) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = HTTPError( 'http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str)) with pytest.raises(Exception) as exc: self.module.check_volume_array_exists(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == "Unable to locate the virtual disk with the ID: v1" @pytest.mark.parametrize("input", [ {"error": URLError("test"), "msg": "<urlopen error test>"} ]) def test_check_volume_array_exists_exceptions(self, redfish_response_mock, redfish_default_args, idrac_connection_mock_for_redfish_storage_controller, input): redfish_default_args.update({"volume_id": ["v1"]}) redfish_response_mock.json_data = {"volume_id": ["v1"]} f_module = self.get_module_mock(params=redfish_default_args) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = input["error"] with pytest.raises(Exception) as exc: self.module.check_volume_array_exists(f_module, idrac_connection_mock_for_redfish_storage_controller) assert exc.value.args[0] == input['msg'] @pytest.mark.parametrize("input", [{"item": "x1"}]) def test_check_id_exists(self, idrac_connection_mock_for_redfish_storage_controller, redfish_response_mock, input): f_module = self.get_module_mock(params=input) msg = "item with id x1 not found in system" redfish_response_mock.success = False with pytest.raises(Exception) as exc: self.module.check_id_exists(f_module, idrac_connection_mock_for_redfish_storage_controller, "item", "uri") assert exc.value.args[0] == msg @pytest.mark.parametrize("input", [ {"error": URLError("test"), "msg": "<urlopen error test>"} ]) def test_check_id_exists_exceptions(self, idrac_connection_mock_for_redfish_storage_controller, input): f_module = self.get_module_mock(params=input) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = input["error"] with pytest.raises(Exception) as exc: self.module.check_id_exists(f_module, idrac_connection_mock_for_redfish_storage_controller, "item", "uri") assert exc.value.args[0] == input['msg'] def test_check_id_exists_HttpError_exceptions(self, idrac_connection_mock_for_redfish_storage_controller, redfish_default_args): f_module = self.get_module_mock(params=redfish_default_args) json_str = to_text(json.dumps({"data": "out"})) idrac_connection_mock_for_redfish_storage_controller.invoke_request.side_effect = HTTPError( 'http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str)) with pytest.raises(Exception) as exc: self.module.check_id_exists(f_module, idrac_connection_mock_for_redfish_storage_controller, "item", "uri") assert exc.value.args[0] == "item with id None not found in system" arg_list1 = [{"command": "ResetConfig", "controller_id": "c1"}, {"command": "RemoveControllerKey", "controller_id": "c1"}, {"command": "ReKey", "controller_id": "c1"}, {"command": "SetControllerKey", "controller_id": "c1", "key": "key", "key_id": "key_id"}, {"command": "AssignSpare", "volume_id": ["v1"], "target": "target"}] @pytest.mark.parametrize("param", arg_list1) def test_idrac_redfish_storage_controller_main_success_case_01(self, mocker, redfish_default_args, redfish_response_mock, idrac_connection_mock_for_redfish_storage_controller, param): mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.validate_inputs') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_raid_service') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_id_exists') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_volume_array_exists') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_encryption_capability') f_module = self.get_module_mock(params=param) redfish_response_mock.success = True redfish_response_mock.headers = {"Location" : "Jobs/1234"} redfish_default_args.update(param) result = self._run_module(redfish_default_args) assert result["changed"] is True assert result['msg'] == "Successfully submitted the job that performs the {0} operation".format(param["command"]) assert result["task"]["id"] == "1234" assert result["task"]["uri"] == "Jobs/1234" arg_list1 = [{"command": "ResetConfig", "controller_id": "c1"}, {"command": "RemoveControllerKey", "controller_id": "c1"}, {"command": "ReKey", "controller_id": "c1"}, {"command": "SetControllerKey", "controller_id": "c1", "key": "key", "key_id": "key_id"}, {"command": "AssignSpare", "target": "target"}] @pytest.mark.parametrize("param", arg_list1) def test_idrac_redfish_storage_controller_main_success_case_02(self, mocker, redfish_default_args, redfish_response_mock, idrac_connection_mock_for_redfish_storage_controller, param): mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.validate_inputs') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_raid_service') mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_id_exists') mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_volume_array_exists') mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_encryption_capability') f_module = self.get_module_mock(params=param) redfish_response_mock.success = True redfish_response_mock.headers = {"Location": "Jobs/1234"} redfish_default_args.update(param) result = self._run_module(redfish_default_args) assert result["changed"] is True assert result['msg'] == "Successfully submitted the job that performs the {0} operation".format( param["command"]) assert result["task"]["id"] == "1234" assert result["task"]["uri"] == "Jobs/1234" @pytest.mark.parametrize("exc_type", [RuntimeError, URLError, SSLValidationError, ConnectionError, KeyError, ImportError, ValueError, TypeError]) def test_idrac_redfish_storage_controller_main_exception_case(self, exc_type, mocker, redfish_default_args, redfish_response_mock, idrac_connection_mock_for_redfish_storage_controller): mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_encryption_capability', side_effect=exc_type('test')) mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_raid_service', side_effect=exc_type('test')) mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_id_exists', side_effect=exc_type('test')) mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_volume_array_exists', side_effect=exc_type('test')) mocker.patch( 'ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.validate_inputs', side_effect=exc_type('test')) result = self._run_module_with_fail_json(redfish_default_args) assert 'power_state' not in result assert 'msg' in result assert result['failed'] is True arg_list1 = [{"command": "ResetConfig", "controller_id": "c1"}, {"command": "RemoveControllerKey", "controller_id": "c1"}, {"command": "ReKey", "controller_id": "c1"}, {"command": "SetControllerKey", "controller_id": "c1", "key": "key", "key_id": "key_id"}, {"command": "AssignSpare", "target": "target"}] @pytest.mark.parametrize("param", arg_list1) def test_idrac_redfish_main_HTTPError_case(self, param, idrac_connection_mock_for_redfish_storage_controller, redfish_default_args, mocker): redfish_default_args.update(param) json_str = to_text(json.dumps({"data": "out"})) mocker.patch('ansible.modules.remote_management.dellemc.idrac_redfish_storage_controller.check_raid_service', side_effect=HTTPError('http://testhost.com', 400, 'http error message', {"accept-type": "application/json"}, StringIO(json_str))) result = self._run_module_with_fail_json(redfish_default_args) assert 'msg' in result assert result['failed'] is True
def test_verify_url_internal_failure(exec_result, expect): check = Kibana(execute_module=lambda *_: dict(failed=True, msg=exec_result)) check._get_kibana_url = lambda: 'url' with pytest.raises(OpenShiftCheckException) as excinfo: check.check_kibana_route() assert expect == excinfo.value.name @pytest.mark.parametrize('lib_result, expect', [ ( HTTPError('url', 500, 'it broke', hdrs=None, fp=None), 'MiscRouteError', ), ( URLError('urlopen error [Errno 111] Connection refused'), 'FailedToConnect', ), ( URLError('urlopen error [Errno -2] Name or service not known'), 'FailedToResolve', ), ( 302, 'WrongReturnCode', ), ( 200, None, ), ])
def test_login_failure(self, mocker): open_url = mocker.patch.object(client, "open_url") open_url.side_effect = URLError("Invalid") with pytest.raises(errors.ClientError): client.Client("http://example.com/", "user", "pass").token