Files
2026-09-12 18:15:20 +08:00

86 lines
2.8 KiB
Python

# -*- coding: utf-8 -*-
"""富文本文件迁移路径修复测试:验证临时文件迁移与URL往返转换。
在临时目录中构建真实的 uploads/temp 结构,确认
save_file 迁移逻辑与路径拼接正确(含 Windows 分隔符场景)。
"""
import sys
import pytest
sys.path.insert(0, 'src')
import utils.rich_text as rt
@pytest.fixture
def fake_uploads(monkeypatch, tmp_path):
"""将 rich_text 的路径常量指向 tmp 下的临时目录。"""
up = tmp_path / 'uploads'
temp = up / 'temp'
temp.mkdir(parents=True)
monkeypatch.setattr(rt, 'FASTAPI_UPLOAD_DIR', str(up))
monkeypatch.setattr(rt, 'FASTAPI_TEMP_PATH', str(temp))
monkeypatch.setattr(rt, 'FASTAPI_FILE_URL', 'http://img.test')
return up, temp
def test_already_in_formal_dir_returns_relative_url(fake_uploads):
up, temp = fake_uploads
target = up / 'article' / '20240801' / 'a.png'
target.parent.mkdir(parents=True)
target.write_bytes(b'x')
result = rt.save_file('http://img.test/article/20240801/a.png', 'article')
assert result == '/article/20240801/a.png'
assert target.exists() # 不迁移、不移动
def test_temp_file_migrates_to_formal_dir(fake_uploads):
import time
up, temp = fake_uploads
src = temp / '20240801' / 'b.png'
src.parent.mkdir(parents=True)
src.write_bytes(b'data')
result = rt.save_file('/temp/20240801/b.png', 'article')
today = time.strftime('%Y%m%d')
# 迁移后返回正式目录相对URL(目标日期目录为当前日期,仅迁移文件名)
assert result == f'/article/{today}/b.png'
assert not src.exists() # 原临时文件已移动
dest = up / 'article' / today / 'b.png'
assert dest.read_bytes() == b'data'
def test_temp_file_migrates_from_absolute_url(fake_uploads):
import time
up, temp = fake_uploads
src = temp / '20240802' / 'c.png'
src.parent.mkdir(parents=True)
src.write_bytes(b'abc')
result = rt.save_file('http://img.test/temp/20240802/c.png', 'article')
today = time.strftime('%Y%m%d')
assert result == f'/article/{today}/c.png'
assert (up / 'article' / today / 'c.png').read_bytes() == b'abc'
def test_remote_url_not_supported(fake_uploads):
assert rt.save_file('https://other.host/x.png', 'article') == ''
def test_empty_url_returns_empty(fake_uploads):
assert rt.save_file('', 'article') == ''
assert rt.save_file(None, 'article') == ''
def test_disk_to_url_roundtrip(fake_uploads):
up, temp = fake_uploads
target = up / 'article' / '20240801' / 'd.png'
target.parent.mkdir(parents=True)
target.write_bytes(b'z')
# 正式目录文件:磁盘路径 -> 相对URL -> 磁盘路径 往返一致
disk = rt._url_to_disk_path('/article/20240801/d.png')
assert disk == str(target)
assert rt._disk_to_url_path(disk) == '/article/20240801/d.png'