Skip to content

Commit

Permalink
Raise LaymanError(46) when invalid style file is uploaded
Browse files Browse the repository at this point in the history
  • Loading branch information
index-git authored and jirik committed Sep 21, 2023
1 parent 993a595 commit 69b9fea
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
22 changes: 14 additions & 8 deletions src/layman/layer/filesystem/input_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 10 additions & 5 deletions src/layman/layer/filesystem/input_style_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import lxml
import pytest
from werkzeug.datastructures import FileStorage

Expand All @@ -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

0 comments on commit 69b9fea

Please sign in to comment.