Skip to content

Commit 553e5b7

Browse files
committed
fix: align base64 io error handling in message components
1 parent 25dc3d6 commit 553e5b7

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

astrbot/core/message/components.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ async def convert_to_base64(self) -> str:
203203
else:
204204
try:
205205
bs64_data = await file_to_base64(self.file)
206-
except (FileNotFoundError, IsADirectoryError) as exc:
206+
except OSError as exc:
207207
raise Exception(f"not a valid file: {self.file}") from exc
208208
bs64_data = bs64_data.removeprefix("base64://")
209209
return bs64_data
@@ -500,7 +500,7 @@ async def convert_to_base64(self) -> str:
500500
else:
501501
try:
502502
bs64_data = await file_to_base64(url)
503-
except (FileNotFoundError, IsADirectoryError) as exc:
503+
except OSError as exc:
504504
raise Exception(f"not a valid file: {url}") from exc
505505
bs64_data = bs64_data.removeprefix("base64://")
506506
return bs64_data

tests/unit/test_message_components_paths.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import pytest
55

6+
from astrbot.core.message import components as components_module
67
from astrbot.core.message.components import File, Image, Record
78

89

@@ -77,3 +78,27 @@ async def test_record_convert_to_base64_reads_existing_local_file(tmp_path):
7778
encoded = await record.convert_to_base64()
7879

7980
assert base64.b64decode(encoded) == raw
81+
82+
83+
@pytest.mark.asyncio
84+
async def test_image_convert_to_base64_maps_permission_error(monkeypatch):
85+
async def _raise_permission_error(_path: str) -> str:
86+
raise PermissionError("permission denied")
87+
88+
monkeypatch.setattr(components_module, "file_to_base64", _raise_permission_error)
89+
90+
image = Image(file="/tmp/forbidden-image")
91+
with pytest.raises(Exception, match="not a valid file"):
92+
await image.convert_to_base64()
93+
94+
95+
@pytest.mark.asyncio
96+
async def test_record_convert_to_base64_maps_permission_error(monkeypatch):
97+
async def _raise_permission_error(_path: str) -> str:
98+
raise PermissionError("permission denied")
99+
100+
monkeypatch.setattr(components_module, "file_to_base64", _raise_permission_error)
101+
102+
record = Record(file="/tmp/forbidden-record")
103+
with pytest.raises(Exception, match="not a valid file"):
104+
await record.convert_to_base64()

0 commit comments

Comments
 (0)