Handle report error on missing svg data (#12514) (#12517)

* Handle report error on missing svg data

* Add regression tests

(cherry picked from commit 76a0005b61)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
This commit is contained in:
github-actions[bot]
2026-08-01 15:48:15 +10:00
committed by GitHub
co-authored by Oliver
parent 2de0bdad51
commit a86a648ccc
2 changed files with 24 additions and 3 deletions
@@ -451,8 +451,13 @@ def uploaded_image(
@register.simple_tag() @register.simple_tag()
def encode_svg_image(filename: str) -> str: def encode_svg_image(filename: str, raise_error: bool = False) -> str:
"""Return a base64-encoded svg image data string.""" """Return a base64-encoded svg image data string.
Arguments:
filename: The filename of the svg image relative to the media root directory
raise_error: If True, raise an error if the file cannot be found (default = False)
"""
if type(filename) is SafeString: if type(filename) is SafeString:
# Prepend an empty string to enforce 'stringiness' # Prepend an empty string to enforce 'stringiness'
filename = '' + filename filename = '' + filename
@@ -465,7 +470,12 @@ def encode_svg_image(filename: str) -> str:
# Read out the file contents # Read out the file contents
# Note: This will check if the file exists, and raise an error if it does not # Note: This will check if the file exists, and raise an error if it does not
data = get_media_file_contents(filename) data = get_media_file_contents(filename, raise_error=raise_error)
# If the file is empty, return an empty string
# Note that if raise_error is True, the above function will raise a FileNotFoundError if the file does not exist
if not data:
return ''
# Return the base64-encoded data # Return the base64-encoded data
return 'data:image/svg+xml;charset=utf-8;base64,' + base64.b64encode(data).decode( return 'data:image/svg+xml;charset=utf-8;base64,' + base64.b64encode(data).decode(
+11
View File
@@ -524,6 +524,17 @@ class ReportTagTest(PartImageTestMixin, InvenTreeTestCase):
svg, svg,
) )
# Test with a missing SVG file - default behavior is to return an empty string
missing_path = 'missing_svg_image_123abc.svg'
self.assertEqual(report_tags.encode_svg_image(missing_path), '')
self.assertEqual(
report_tags.encode_svg_image(missing_path, raise_error=False), ''
)
# Test with a missing SVG file, with raise_error=True
with self.assertRaises(FileNotFoundError):
report_tags.encode_svg_image(missing_path, raise_error=True)
def test_part_parameter(self): def test_part_parameter(self):
"""Test the part_parameter template tag.""" """Test the part_parameter template tag."""
# Test with a valid part # Test with a valid part