"""抖音分享文本 URL 提取单测。""" from __future__ import annotations import pytest # 直接 import 模块,用 _extract_url_from_text / _extract_and_validate_douyin_url 测试 from app.api.routes.scripts_ai import ( _extract_and_validate_douyin_url, _extract_url_from_text, ) from fastapi import HTTPException, status class TestExtractUrlFromText: def test_pure_url(self): assert _extract_url_from_text("https://v.douyin.com/iZ7vU2qH/") == "https://v.douyin.com/iZ7vU2qH/" def test_share_text_with_prefix_suffix(self): """典型"复制链接"场景:包含中文+表情+链接+话题标签。""" s = "这个视频太搞笑了 https://v.douyin.com/iZ7vU2qH/ 快来看看!#搞笑 #日常" assert _extract_url_from_text(s) == "https://v.douyin.com/iZ7vU2qH/" def test_share_text_no_http_prefix(self): s = "复制此链接,打开Dou音搜索,直接观看视频!v.douyin.com/iZ7vU2qH/" # Should pick up v.douyin.com/... and add https:// prefix url = _extract_url_from_text(s) assert url and url.endswith("v.douyin.com/iZ7vU2qH/") def test_long_url_www(self): s = "https://www.douyin.com/video/7234567890123456789?previous_page=web_code_link" assert _extract_url_from_text(s) == s def test_empty_input(self): assert _extract_url_from_text("") is None assert _extract_url_from_text(None) is None # type: ignore[arg-type] def test_no_url(self): assert _extract_url_from_text("这个视频很好看,但是没有链接") is None def test_trailing_punct_stripped(self): s = "https://v.douyin.com/iZ7vU2qH/。" assert _extract_url_from_text(s) == "https://v.douyin.com/iZ7vU2qH/" class TestValidateUrl: def test_pure_short_url_ok(self): assert _extract_and_validate_douyin_url("https://v.douyin.com/iZ7vU2qH/").startswith("https://") def test_share_text_ok(self): s = "这个视频太搞笑了 https://v.douyin.com/abcdefG/ 快来看看!" url = _extract_and_validate_douyin_url(s) assert "douyin.com" in url def test_empty_raises_400(self): with pytest.raises(HTTPException) as ei: _extract_and_validate_douyin_url("") assert ei.value.status_code == 400 def test_no_url_raises_400(self): with pytest.raises(HTTPException) as ei: _extract_and_validate_douyin_url("这个视频没有链接") assert ei.value.status_code == 400 def test_non_douyin_raises_400(self): with pytest.raises(HTTPException) as ei: _extract_and_validate_douyin_url("https://www.bilibili.com/video/BV1xx411c7mD") assert ei.value.status_code == 400 def test_scheme_added_when_missing(self): """只输入 v.douyin.com/xxx 时,补 https://。""" url = _extract_and_validate_douyin_url("v.douyin.com/iZ7vU2qH/") assert url.startswith("https://")