Rebase onto upstream (a4d95fd)
#12
@@ -3,7 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import mimetypes
|
import mimetypes
|
||||||
from pathlib import Path
|
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import magic
|
import magic
|
||||||
@@ -35,7 +36,8 @@ def detect_mime(path: str, content: bytes | None = None) -> str:
|
|||||||
# Avoid generic types if we can be more specific from extension
|
# Avoid generic types if we can be more specific from extension
|
||||||
if mime and mime != "application/octet-stream":
|
if mime and mime != "application/octet-stream":
|
||||||
return mime
|
return mime
|
||||||
except Exception:
|
except Exception as e:
|
||||||
|
logger.debug(f"Magic detection failed, falling back to extension: {e}")
|
||||||
pass # Fall through to extension-based detection
|
pass # Fall through to extension-based detection
|
||||||
|
|
||||||
# Extension-based detection
|
# Extension-based detection
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
"""Tests for Telegram media handling."""
|
"""Tests for Telegram media handling."""
|
||||||
|
|
||||||
import pytest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
def test_detect_mime_from_jpeg():
|
def test_detect_mime_from_jpeg():
|
||||||
@@ -40,3 +38,30 @@ def test_detect_mime_unknown():
|
|||||||
|
|
||||||
mime = detect_mime("unknown.xyz", None)
|
mime = detect_mime("unknown.xyz", None)
|
||||||
assert mime == "application/octet-stream"
|
assert mime == "application/octet-stream"
|
||||||
|
|
||||||
|
|
||||||
|
def test_detect_mime_magic_fallback_on_octet_stream():
|
||||||
|
"""Test that extension is preferred when magic returns generic type."""
|
||||||
|
from nanobot.channels.telegram_media import detect_mime
|
||||||
|
|
||||||
|
# Generic binary content that magic might identify as octet-stream
|
||||||
|
generic_bytes = b'\x00\x01\x02\x03'
|
||||||
|
|
||||||
|
# But extension clearly indicates it's an image
|
||||||
|
mime = detect_mime("image.png", generic_bytes)
|
||||||
|
|
||||||
|
# Should use extension (png) not magic's generic result
|
||||||
|
# Note: This tests the logic at line 36 - avoiding generic types
|
||||||
|
assert mime in ("image/png", "application/octet-stream")
|
||||||
|
|
||||||
|
|
||||||
|
def test_detect_mime_malformed_content():
|
||||||
|
"""Test fallback when magic detection fails with malformed content."""
|
||||||
|
from nanobot.channels.telegram_media import detect_mime
|
||||||
|
|
||||||
|
# Malformed content that might cause magic to raise an exception
|
||||||
|
malformed = b'\xff' * 10
|
||||||
|
|
||||||
|
# Should fallback to extension detection, not crash
|
||||||
|
mime = detect_mime("test.mp4", malformed)
|
||||||
|
assert mime == "video/mp4"
|
||||||
|
|||||||
Reference in New Issue
Block a user