diff --git a/src/layman/layer/filesystem/input_style.py b/src/layman/layer/filesystem/input_style.py index b1bb7dd3f..f4d5de034 100644 --- a/src/layman/layer/filesystem/input_style.py +++ b/src/layman/layer/filesystem/input_style.py @@ -73,14 +73,20 @@ def get_layer_file(workspace, layername): def get_style_type_from_file_storage(file_storage): if file_storage: - xml = file_storage.read() - file_storage.seek(0) - xml_tree = etree.fromstring(xml) - root_tag = xml_tree.tag - root_attribute = etree.QName(root_tag).localname - result = next((sd for sd in layer.STYLE_TYPES_DEF if sd.root_element == root_attribute), None) - if not result: - raise LaymanError(46) + try: + xml = file_storage.read() + file_storage.seek(0) + xml_tree = etree.fromstring(xml) + root_tag = xml_tree.tag + root_attribute = etree.QName(root_tag).localname + result = next((sd for sd in layer.STYLE_TYPES_DEF if sd.root_element == root_attribute), None) + if not result: + raise LaymanError(46, { + 'message': f"Unknown root element.", + 'expected': f"Root element is one of {[sd.root_element for sd in layer.STYLE_TYPES_DEF if sd.root_element]}", + }) + except etree.XMLSyntaxError as exc: + raise LaymanError(46, "Unable to parse style file.",) from exc else: result = layer.NO_STYLE_DEF return result diff --git a/src/layman/layer/filesystem/input_style_test.py b/src/layman/layer/filesystem/input_style_test.py index 205a3be77..8e7aa53fd 100644 --- a/src/layman/layer/filesystem/input_style_test.py +++ b/src/layman/layer/filesystem/input_style_test.py @@ -1,4 +1,3 @@ -import lxml import pytest from werkzeug.datastructures import FileStorage @@ -23,15 +22,21 @@ def test_get_style_type_from_xml_file(file_path, assert detected_type.code == expected_type -@pytest.mark.parametrize('file_path, expected_error, expected_code', [ - ('sample/style/no_style.xml', LaymanError, 46), - ('test_tools/data/thumbnail/countries_wms_blue.png', lxml.etree.XMLSyntaxError, 4), +@pytest.mark.parametrize('file_path, expected_error, expected_code, expected_data', [ + ('sample/style/no_style.xml', LaymanError, 46, { + 'message': 'Unknown root element.', + 'expected': "Root element is one of ['StyledLayerDescriptor', 'qgis']", + }), + ('sample/style/generic-invalid.xml', LaymanError, 46, 'Unable to parse style file.'), + ('test_tools/data/thumbnail/countries_wms_blue.png', LaymanError, 46, 'Unable to parse style file.'), ]) def test_get_style_type_from_xml_file_errors(file_path, expected_error, - expected_code): + expected_code, + expected_data): with pytest.raises(expected_error) as exc_info: with open(file_path, 'rb') as file: file = FileStorage(file) input_style.get_style_type_from_file_storage(file) assert exc_info.value.code == expected_code + assert exc_info.value.data == expected_data