Files
hiking_assistant/tests/test_utils.py
2025-11-29 06:56:07 +08:00

63 lines
2.1 KiB
Python

# test_utils.py
#
# author: deng
# date: 20251129
import base64
import tempfile
from pathlib import Path
import pytest
class TestConvertImageToBase64:
"""Test cases for convert_image_to_base64 function."""
@pytest.fixture
def temp_image_file(self):
"""Create a temporary image file for testing."""
with tempfile.NamedTemporaryFile(mode='wb', suffix='.jpg', delete=False) as f:
# Create a simple test image (1x1 red pixel)
f.write(b'\xff\xd8\xff\xe0\x00\x10JFIF') # JPEG header
temp_path = f.name
yield temp_path
# Cleanup
Path(temp_path).unlink(missing_ok=True)
def test_convert_image_to_base64_returns_string(self, temp_image_file):
"""Test that function returns a string."""
from hiking_assistant.utils import convert_image_to_base64
result = convert_image_to_base64(temp_image_file)
assert isinstance(result, str)
def test_convert_image_to_base64_returns_valid_base64(self, temp_image_file):
"""Test that returned string is valid base64."""
from hiking_assistant.utils import convert_image_to_base64
result = convert_image_to_base64(temp_image_file)
# Try to decode - should not raise exception
decoded = base64.b64decode(result)
assert isinstance(decoded, bytes)
def test_convert_image_to_base64_roundtrip(self, temp_image_file):
"""Test roundtrip conversion (file -> base64 -> binary)."""
from hiking_assistant.utils import convert_image_to_base64
# Read original file
with open(temp_image_file, 'rb') as f:
original_data = f.read()
# Convert to base64 and back
base64_str = convert_image_to_base64(temp_image_file)
decoded_data = base64.b64decode(base64_str)
assert decoded_data == original_data
def test_convert_image_to_base64_nonexistent_file_raises_error(self):
"""Test that function raises error for non-existent file."""
from hiking_assistant.utils import convert_image_to_base64
with pytest.raises(FileNotFoundError):
convert_image_to_base64('/nonexistent/path/to/image.jpg')