Files
AstrBot/tests/unit/test_webchat_upload_image_format.py
Niansia 42972e932a fix(dashboard): store chat attachments under unique names (#10356)
* fix(dashboard): store chat attachments under unique names

Uploads were saved under their original filename, so two attachments with
the same name (every pasted screenshot is image.png) overwrote each other,
and deleting one session removed a file another session still used.

Store each upload as <timestamp id>_<name> and return the original name as
`filename` for display, with the on-disk name in `stored_filename`.

Fixes #10352

* fix(dashboard): keep long-suffix attachment names within 255 bytes
2026-10-04 13:09:16 +08:00

84 lines
2.5 KiB
Python

from io import BytesIO
from types import SimpleNamespace
import pytest
from PIL import Image as PILImage
from astrbot.dashboard.services.chat_service import (
WEBCHAT_IMAGE_MIME_TYPES,
ChatService,
)
@pytest.mark.asyncio
async def test_webchat_upload_uses_detected_image_type(tmp_path):
image_buffer = BytesIO()
PILImage.new("RGB", (2, 2), (255, 0, 0)).save(image_buffer, format="JPEG")
class FakeUploadFile:
filename = "pasted.png"
content_type = "image/png"
content_length = None
async def save(self, destination, *, max_bytes=None):
with open(destination, "wb") as output:
output.write(image_buffer.getvalue())
class FakeDatabase:
def __init__(self):
self.inserted = None
async def insert_attachment(self, path, type, mime_type):
self.inserted = {
"path": path,
"type": type,
"mime_type": mime_type,
}
return SimpleNamespace(attachment_id="attachment-1", path=path)
fake_db = FakeDatabase()
service = ChatService.__new__(ChatService)
service.db = fake_db
service.attachments_dir = str(tmp_path)
result = await service.save_uploaded_file(FakeUploadFile())
assert result["filename"] == "pasted.jpg"
assert fake_db.inserted["mime_type"] == "image/jpeg"
assert fake_db.inserted["type"] == "image"
assert result["stored_filename"].endswith("_pasted.jpg")
assert (tmp_path / result["stored_filename"]).exists()
assert not list(tmp_path.glob("*.png"))
@pytest.mark.parametrize(
("filename", "expected_mime_type"),
[(f"photo{ext}", mime_type) for ext, mime_type in WEBCHAT_IMAGE_MIME_TYPES.items()],
)
@pytest.mark.asyncio
async def test_resolve_webchat_file_uses_image_extension_mime_type(
tmp_path,
monkeypatch,
filename,
expected_mime_type,
):
monkeypatch.setattr(
"astrbot.dashboard.services.chat_service.get_astrbot_data_path",
lambda: str(tmp_path),
)
service = ChatService(
SimpleNamespace(),
SimpleNamespace(
conversation_manager=None,
platform_message_history_manager=None,
umop_config_router=None,
),
)
file_path = tmp_path / "attachments" / filename
file_path.write_bytes(b"image-bytes")
resolved_path, mime_type = await service.resolve_webchat_file(filename)
assert resolved_path == str(file_path.resolve(strict=False))
assert mime_type == expected_mime_type