Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2205cb9903 | |||
| 87a3351aba | |||
| 39187a0660 | |||
| f0bbedab23 | |||
| 750444c8bb | |||
| 581a146d2f | |||
| eab45e0819 | |||
| e243d70082 | |||
| d4c3743e45 |
@@ -1805,7 +1805,7 @@ jobs:
|
||||
echo "❌ CI Gate: FAILED"
|
||||
echo "失败项: ${FAILED_ITEMS[*]}"
|
||||
echo "gate_result=failure" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Report CI trace
|
||||
|
||||
Regular → Executable
+5
-81
@@ -1,11 +1,10 @@
|
||||
import React, { useState, useRef } from "react"
|
||||
import { UploadOutlined, SoundOutlined, CloseOutlined } from "@ant-design/icons"
|
||||
import React, { useState } from "react"
|
||||
import { Button, Input } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { type VoiceGender, type VoiceMaterial } from "../types"
|
||||
import { GENDER_OPTIONS } from "../constants"
|
||||
import { genderClass, formatFileSize } from "../utils/format"
|
||||
import TagSelector from "./TagSelector"
|
||||
import FileUploadField from "./material-form/FileUploadField"
|
||||
import GenderSelector from "./material-form/GenderSelector"
|
||||
|
||||
export interface MaterialFormProps {
|
||||
initial?: VoiceMaterial
|
||||
@@ -33,7 +32,6 @@ const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
const [gender, setGender] = useState<VoiceGender>(initial?.gender ?? "female")
|
||||
const [selectedTagIds, setSelectedTagIds] = useState<string[]>(initial?.tagIds ?? [])
|
||||
const [file, setFile] = useState<File | undefined>(undefined)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!name.trim()) return
|
||||
@@ -53,65 +51,10 @@ const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
|
||||
return (
|
||||
<div className="vmat-form">
|
||||
{/* 音频文件上传(编辑模式不显示) */}
|
||||
{!initial && (
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">音频文件 *</label>
|
||||
<div
|
||||
className="vmat-upload-zone"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
const f = e.dataTransfer.files[0]
|
||||
if (f?.type.startsWith("audio/")) setFile(f)
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) setFile(f)
|
||||
}}
|
||||
/>
|
||||
{file ? (
|
||||
<div className="vmat-upload-selected">
|
||||
<SoundOutlined className="vmat-upload-icon" />
|
||||
<span className="vmat-upload-filename">{file.name}</span>
|
||||
<span className="vmat-upload-filesize">{formatFileSize(file.size)}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-upload-clear"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setFile(undefined)
|
||||
}}
|
||||
>
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="vmat-upload-placeholder">
|
||||
<UploadOutlined className="vmat-upload-icon" />
|
||||
<p>点击或拖拽音频文件到此处</p>
|
||||
<span>支持 MP3、WAV、AAC、FLAC 等格式</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* 上传进度条 */}
|
||||
{uploadProgress !== null && uploadProgress !== undefined && (
|
||||
<div className="vmat-upload-progress">
|
||||
<div className="vmat-upload-progress-bar" style={{ width: `${uploadProgress}%` }} />
|
||||
<span className="vmat-upload-progress-text">{uploadProgress}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<FileUploadField file={file} onChange={setFile} uploadProgress={uploadProgress} />
|
||||
)}
|
||||
|
||||
{/* 名称 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">名称 *</label>
|
||||
<Input
|
||||
@@ -122,7 +65,6 @@ const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 音色描述 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">音色描述</label>
|
||||
<Input.TextArea
|
||||
@@ -134,25 +76,8 @@ const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 性别 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">性别</label>
|
||||
<div className="vmat-gender-group">
|
||||
{GENDER_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
className={`vmat-gender-btn${gender === opt.value ? " active" : ""} ${genderClass(opt.value)}`}
|
||||
onClick={() => setGender(opt.value)}
|
||||
>
|
||||
{opt.icon}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<GenderSelector value={gender} onChange={setGender} />
|
||||
|
||||
{/* 风格标签 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">风格标签</label>
|
||||
<TagSelector
|
||||
@@ -164,7 +89,6 @@ const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="vmat-form-actions">
|
||||
<Button buttonType="ghost" buttonSize="md" onClick={onCancel}>
|
||||
取消
|
||||
|
||||
Regular → Executable
+16
-72
@@ -1,7 +1,8 @@
|
||||
import React, { useState, useRef, useCallback, useMemo } from "react"
|
||||
import React from "react"
|
||||
import { CheckOutlined } from "@ant-design/icons"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import type { TagItem } from "@/api/tags"
|
||||
import { useTagInput } from "./tag-selector/useTagInput"
|
||||
|
||||
export interface TagSelectorProps {
|
||||
/** 已选标签 ID 列表 */
|
||||
@@ -24,77 +25,22 @@ const TagSelector: React.FC<TagSelectorProps> = ({
|
||||
onCreateTag,
|
||||
placeholder = "输入标签后回车添加",
|
||||
}) => {
|
||||
const [inputVal, setInputVal] = useState("")
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
/** 按名称查找已有标签(大小写不敏感) */
|
||||
const findTagByName = useCallback(
|
||||
(name: string) => tags.find((t) => t.name.toLowerCase() === name.toLowerCase()),
|
||||
[tags],
|
||||
)
|
||||
|
||||
/** 去重添加标签(按 ID) */
|
||||
const addTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
if (value.includes(tagId)) return
|
||||
onChange([...value, tagId])
|
||||
setInputVal("")
|
||||
setShowSuggestions(false)
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
/** 输入自定义标签名:若已存在则直接选,否则创建新标签 */
|
||||
const addTagByName = useCallback(
|
||||
async (name: string) => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) return
|
||||
const existing = findTagByName(trimmed)
|
||||
if (existing) {
|
||||
addTagId(existing.id)
|
||||
} else {
|
||||
try {
|
||||
const created = await onCreateTag(trimmed)
|
||||
addTagId(created.id)
|
||||
} catch {
|
||||
/* 创建失败静默忽略 */
|
||||
}
|
||||
}
|
||||
},
|
||||
[findTagByName, addTagId, onCreateTag],
|
||||
)
|
||||
|
||||
const removeTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
onChange(value.filter((t) => t !== tagId))
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
/** 输入补全建议(排除已选) */
|
||||
const suggestions = useMemo(() => {
|
||||
if (!inputVal.trim()) return []
|
||||
const lower = inputVal.toLowerCase()
|
||||
return tags.filter((t) => t.name.toLowerCase().includes(lower) && !value.includes(t.id))
|
||||
}, [inputVal, tags, value])
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
if (suggestions.length > 0) {
|
||||
addTagId(suggestions[0].id)
|
||||
} else {
|
||||
addTagByName(inputVal)
|
||||
}
|
||||
} else if (e.key === "Backspace" && !inputVal && value.length > 0) {
|
||||
removeTagId(value[value.length - 1])
|
||||
}
|
||||
}
|
||||
const {
|
||||
inputVal,
|
||||
setInputVal,
|
||||
showSuggestions,
|
||||
setShowSuggestions,
|
||||
inputRef,
|
||||
suggestions,
|
||||
addTagId,
|
||||
removeTagId,
|
||||
handleKeyDown,
|
||||
focus,
|
||||
} = useTagInput({ value, onChange, tags, onCreateTag })
|
||||
|
||||
return (
|
||||
<div className="vmat-tag-selector-wrapper">
|
||||
<div className="vmat-tag-selector" onClick={() => inputRef.current?.focus()}>
|
||||
<div className="vmat-tag-selector" onClick={focus}>
|
||||
{value.map((tagId) => (
|
||||
<Tag key={tagId} variant="info" closable onClose={() => removeTagId(tagId)}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
@@ -115,7 +61,6 @@ const TagSelector: React.FC<TagSelectorProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 自动补全下拉 */}
|
||||
{showSuggestions && suggestions.length > 0 && (
|
||||
<div className="vmat-tag-suggestions">
|
||||
{suggestions.slice(0, 6).map((tag) => (
|
||||
@@ -134,7 +79,6 @@ const TagSelector: React.FC<TagSelectorProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 已有标签快捷选择 */}
|
||||
{tags.length > 0 && (
|
||||
<div className="vmat-tag-selector-presets">
|
||||
{tags.map((tag) => {
|
||||
|
||||
Regular → Executable
+9
-57
@@ -1,4 +1,4 @@
|
||||
import React, { useRef } from "react"
|
||||
import React from "react"
|
||||
import {
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
@@ -6,11 +6,8 @@ import {
|
||||
DeleteOutlined,
|
||||
CheckOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { Tooltip } from "antd"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { type VoiceMaterial } from "../types"
|
||||
import { MAX_ROW_TAGS, TAG_VARIANTS } from "../constants"
|
||||
import {
|
||||
genderClass,
|
||||
genderIcon,
|
||||
@@ -18,6 +15,8 @@ import {
|
||||
formatDuration,
|
||||
formatFileSize,
|
||||
} from "../utils/format"
|
||||
import { useRowProgress } from "./voice-material-row/useRowProgress"
|
||||
import TagDisplay from "./voice-material-row/TagDisplay"
|
||||
|
||||
export interface VoiceRowProps {
|
||||
material: VoiceMaterial
|
||||
@@ -48,26 +47,10 @@ const VoiceMaterialRow: React.FC<VoiceRowProps> = ({
|
||||
onDelete,
|
||||
onToggleSelect,
|
||||
}) => {
|
||||
const progressRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleProgressMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!progressRef.current) return
|
||||
e.preventDefault()
|
||||
const doSeek = (ev: MouseEvent) => {
|
||||
if (!progressRef.current) return
|
||||
const rect = progressRef.current.getBoundingClientRect()
|
||||
const percent = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width))
|
||||
onSeek(percent * material.duration)
|
||||
}
|
||||
doSeek(e.nativeEvent)
|
||||
const handleMove = (ev: MouseEvent) => doSeek(ev)
|
||||
const handleUp = () => {
|
||||
document.removeEventListener("mousemove", handleMove)
|
||||
document.removeEventListener("mouseup", handleUp)
|
||||
}
|
||||
document.addEventListener("mousemove", handleMove)
|
||||
document.addEventListener("mouseup", handleUp)
|
||||
}
|
||||
const { progressRef, handleMouseDown } = useRowProgress({
|
||||
duration: material.duration,
|
||||
onSeek,
|
||||
})
|
||||
|
||||
const progress = material.duration > 0 ? (currentTime / material.duration) * 100 : 0
|
||||
|
||||
@@ -75,7 +58,6 @@ const VoiceMaterialRow: React.FC<VoiceRowProps> = ({
|
||||
<div
|
||||
className={`vmat-row ${genderClass(material.gender)}${isPlaying ? " playing" : ""}${isSelected ? " selected" : ""}${batchMode ? " batch-mode" : ""}`}
|
||||
>
|
||||
{/* 批量选择 checkbox */}
|
||||
{(batchMode || isSelected) && (
|
||||
<div
|
||||
className={`vmat-row-checkbox vmat-checkbox${isSelected ? " checked" : ""}`}
|
||||
@@ -88,7 +70,6 @@ const VoiceMaterialRow: React.FC<VoiceRowProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 播放按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-row-play"
|
||||
@@ -101,60 +82,31 @@ const VoiceMaterialRow: React.FC<VoiceRowProps> = ({
|
||||
{isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
|
||||
</button>
|
||||
|
||||
{/* 名称 + 描述 */}
|
||||
<div className="vmat-row-info">
|
||||
<h4 className="vmat-row-name">{material.name}</h4>
|
||||
{material.description && <p className="vmat-row-desc">{material.description}</p>}
|
||||
</div>
|
||||
|
||||
{/* 性别 */}
|
||||
<span className={`vmat-row-gender ${genderClass(material.gender)}`}>
|
||||
{genderIcon(material.gender)}
|
||||
{genderLabel(material.gender)}
|
||||
</span>
|
||||
|
||||
{/* 标签 */}
|
||||
<div className="vmat-row-tags">
|
||||
{material.tagIds.length === 0 ? (
|
||||
<span className="vmat-tag-empty" onClick={() => onEdit()}>
|
||||
添加标签
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{material.tagIds.slice(0, MAX_ROW_TAGS).map((tagId, i) => (
|
||||
<Tag key={tagId} variant={TAG_VARIANTS[i % TAG_VARIANTS.length]}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
</Tag>
|
||||
))}
|
||||
{material.tagIds.length > MAX_ROW_TAGS && (
|
||||
<Tooltip
|
||||
title={material.tagIds
|
||||
.slice(MAX_ROW_TAGS)
|
||||
.map((id) => tagMap.get(id)?.name ?? id)
|
||||
.join("、")}
|
||||
>
|
||||
<Tag className="vmat-tag-overflow">+{material.tagIds.length - MAX_ROW_TAGS}</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<TagDisplay tagIds={material.tagIds} tagMap={tagMap} onAddTag={() => onEdit()} />
|
||||
</div>
|
||||
|
||||
{/* 进度条(可拖拽) */}
|
||||
<div ref={progressRef} className="vmat-row-progress" onMouseDown={handleProgressMouseDown}>
|
||||
<div ref={progressRef} className="vmat-row-progress" onMouseDown={handleMouseDown}>
|
||||
<div className="vmat-row-progress-bar" style={{ width: `${progress}%` }} />
|
||||
{isPlaying && <div className="vmat-progress-thumb" style={{ left: `${progress}%` }} />}
|
||||
</div>
|
||||
|
||||
{/* 时长 */}
|
||||
<span className="vmat-row-time">
|
||||
{isPlaying ? formatDuration(currentTime) : formatDuration(material.duration)}
|
||||
</span>
|
||||
|
||||
{/* 文件大小 */}
|
||||
<span className="vmat-row-size">{formatFileSize(material.fileSize)}</span>
|
||||
|
||||
{/* 操作 */}
|
||||
<div className="vmat-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import React, { useRef } from "react"
|
||||
import { UploadOutlined, SoundOutlined, CloseOutlined } from "@ant-design/icons"
|
||||
import { formatFileSize } from "../../utils/format"
|
||||
|
||||
interface FileUploadFieldProps {
|
||||
file: File | undefined
|
||||
onChange: (file: File | undefined) => void
|
||||
uploadProgress?: number | null
|
||||
}
|
||||
|
||||
const FileUploadField: React.FC<FileUploadFieldProps> = ({ file, onChange, uploadProgress }) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
const f = e.dataTransfer.files[0]
|
||||
if (f?.type.startsWith("audio/")) onChange(f)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">音频文件 *</label>
|
||||
<div
|
||||
className="vmat-upload-zone"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) onChange(f)
|
||||
}}
|
||||
/>
|
||||
{file ? (
|
||||
<div className="vmat-upload-selected">
|
||||
<SoundOutlined className="vmat-upload-icon" />
|
||||
<span className="vmat-upload-filename">{file.name}</span>
|
||||
<span className="vmat-upload-filesize">{formatFileSize(file.size)}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-upload-clear"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onChange(undefined)
|
||||
}}
|
||||
>
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="vmat-upload-placeholder">
|
||||
<UploadOutlined className="vmat-upload-icon" />
|
||||
<p>点击或拖拽音频文件到此处</p>
|
||||
<span>支持 MP3、WAV、AAC、FLAC 等格式</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{uploadProgress !== null && uploadProgress !== undefined && (
|
||||
<div className="vmat-upload-progress">
|
||||
<div className="vmat-upload-progress-bar" style={{ width: `${uploadProgress}%` }} />
|
||||
<span className="vmat-upload-progress-text">{uploadProgress}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FileUploadField
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import React from "react"
|
||||
import type { VoiceGender } from "../../types"
|
||||
import { GENDER_OPTIONS } from "../../constants"
|
||||
import { genderClass } from "../../utils/format"
|
||||
|
||||
interface GenderSelectorProps {
|
||||
value: VoiceGender
|
||||
onChange: (value: VoiceGender) => void
|
||||
}
|
||||
|
||||
const GenderSelector: React.FC<GenderSelectorProps> = ({ value, onChange }) => {
|
||||
return (
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">性别</label>
|
||||
<div className="vmat-gender-group">
|
||||
{GENDER_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
className={`vmat-gender-btn${value === opt.value ? " active" : ""} ${genderClass(opt.value)}`}
|
||||
onClick={() => onChange(opt.value)}
|
||||
>
|
||||
{opt.icon}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default GenderSelector
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState, useRef, useCallback, useMemo } from "react"
|
||||
import type { TagItem } from "@/api/tags"
|
||||
|
||||
interface UseTagInputOptions {
|
||||
value: string[]
|
||||
onChange: (tagIds: string[]) => void
|
||||
tags: TagItem[]
|
||||
onCreateTag: (name: string) => Promise<TagItem>
|
||||
}
|
||||
|
||||
export function useTagInput({ value, onChange, tags, onCreateTag }: UseTagInputOptions) {
|
||||
const [inputVal, setInputVal] = useState("")
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const findTagByName = useCallback(
|
||||
(name: string) => tags.find((t) => t.name.toLowerCase() === name.toLowerCase()),
|
||||
[tags],
|
||||
)
|
||||
|
||||
const addTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
if (value.includes(tagId)) return
|
||||
onChange([...value, tagId])
|
||||
setInputVal("")
|
||||
setShowSuggestions(false)
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
const addTagByName = useCallback(
|
||||
async (name: string) => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) return
|
||||
const existing = findTagByName(trimmed)
|
||||
if (existing) {
|
||||
addTagId(existing.id)
|
||||
} else {
|
||||
try {
|
||||
const created = await onCreateTag(trimmed)
|
||||
addTagId(created.id)
|
||||
} catch {
|
||||
/* 创建失败静默忽略 */
|
||||
}
|
||||
}
|
||||
},
|
||||
[findTagByName, addTagId, onCreateTag],
|
||||
)
|
||||
|
||||
const removeTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
onChange(value.filter((t) => t !== tagId))
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
const suggestions = useMemo(() => {
|
||||
if (!inputVal.trim()) return []
|
||||
const lower = inputVal.toLowerCase()
|
||||
return tags.filter((t) => t.name.toLowerCase().includes(lower) && !value.includes(t.id))
|
||||
}, [inputVal, tags, value])
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
if (suggestions.length > 0) {
|
||||
addTagId(suggestions[0].id)
|
||||
} else {
|
||||
addTagByName(inputVal)
|
||||
}
|
||||
} else if (e.key === "Backspace" && !inputVal && value.length > 0) {
|
||||
removeTagId(value[value.length - 1])
|
||||
}
|
||||
}
|
||||
|
||||
const focus = () => inputRef.current?.focus()
|
||||
|
||||
return {
|
||||
inputVal,
|
||||
setInputVal,
|
||||
showSuggestions,
|
||||
setShowSuggestions,
|
||||
inputRef,
|
||||
suggestions,
|
||||
addTagId,
|
||||
removeTagId,
|
||||
handleKeyDown,
|
||||
focus,
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import React from "react"
|
||||
import { Tooltip } from "antd"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { MAX_ROW_TAGS, TAG_VARIANTS } from "../../constants"
|
||||
|
||||
interface TagDisplayProps {
|
||||
tagIds: string[]
|
||||
tagMap: Map<string, TagItem>
|
||||
onAddTag?: () => void
|
||||
}
|
||||
|
||||
const TagDisplay: React.FC<TagDisplayProps> = ({ tagIds, tagMap, onAddTag }) => {
|
||||
if (tagIds.length === 0) {
|
||||
return (
|
||||
<span className="vmat-tag-empty" onClick={onAddTag}>
|
||||
添加标签
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const visible = tagIds.slice(0, MAX_ROW_TAGS)
|
||||
const overflow = tagIds.slice(MAX_ROW_TAGS)
|
||||
|
||||
return (
|
||||
<>
|
||||
{visible.map((tagId, i) => (
|
||||
<Tag key={tagId} variant={TAG_VARIANTS[i % TAG_VARIANTS.length]}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
</Tag>
|
||||
))}
|
||||
{overflow.length > 0 && (
|
||||
<Tooltip title={overflow.map((id) => tagMap.get(id)?.name ?? id).join("、")}>
|
||||
<Tag className="vmat-tag-overflow">+{overflow.length}</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default TagDisplay
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { useRef, useCallback } from "react"
|
||||
|
||||
interface UseRowProgressOptions {
|
||||
duration: number
|
||||
onSeek: (time: number) => void
|
||||
}
|
||||
|
||||
export function useRowProgress({ duration, onSeek }: UseRowProgressOptions) {
|
||||
const progressRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleMouseDown = useCallback(
|
||||
(e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!progressRef.current) return
|
||||
e.preventDefault()
|
||||
|
||||
const doSeek = (ev: MouseEvent) => {
|
||||
if (!progressRef.current) return
|
||||
const rect = progressRef.current.getBoundingClientRect()
|
||||
const percent = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width))
|
||||
onSeek(percent * duration)
|
||||
}
|
||||
|
||||
doSeek(e.nativeEvent)
|
||||
|
||||
const handleMove = (ev: MouseEvent) => doSeek(ev)
|
||||
const handleUp = () => {
|
||||
document.removeEventListener("mousemove", handleMove)
|
||||
document.removeEventListener("mouseup", handleUp)
|
||||
}
|
||||
|
||||
document.addEventListener("mousemove", handleMove)
|
||||
document.addEventListener("mouseup", handleUp)
|
||||
},
|
||||
[duration, onSeek],
|
||||
)
|
||||
|
||||
return { progressRef, handleMouseDown }
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react"
|
||||
import { type VoiceMaterial } from "../../../types"
|
||||
import { type VoiceMaterial } from "../../types"
|
||||
import { type AssetLibraryItem } from "@/api/assets"
|
||||
import { useVoiceUpload } from "./actions/useVoiceUpload"
|
||||
import { useVoiceEdit } from "./actions/useVoiceEdit"
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
import React from "react"
|
||||
import {
|
||||
SoundOutlined,
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
DeleteOutlined,
|
||||
ReloadOutlined,
|
||||
CloseCircleOutlined,
|
||||
UserOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { DeleteOutlined, ReloadOutlined, CloseCircleOutlined } from "@ant-design/icons"
|
||||
import { Tooltip } from "antd"
|
||||
import { type ClonedVoiceDisplay } from "@/pages/voices/types"
|
||||
import { CLONE_STATUS_CONFIG } from "@/pages/voices/constants"
|
||||
import CardHeader from "./clone-voice-card/CardHeader"
|
||||
import CardFooter from "./clone-voice-card/CardFooter"
|
||||
|
||||
export interface CloneVoiceCardProps {
|
||||
voice: ClonedVoiceDisplay
|
||||
@@ -28,26 +21,18 @@ export interface CloneVoiceCardProps {
|
||||
const CloneVoiceCard: React.FC<CloneVoiceCardProps> = ({
|
||||
voice,
|
||||
isPlaying,
|
||||
currentTime,
|
||||
onPlay,
|
||||
onPause,
|
||||
onUse,
|
||||
onDelete,
|
||||
onRetry,
|
||||
onShowDetail,
|
||||
...footerProps
|
||||
}) => {
|
||||
const statusCfg = CLONE_STATUS_CONFIG[voice.status]
|
||||
const isFailed = voice.status === "failed"
|
||||
const isProcessing = voice.status === "processing"
|
||||
const genderText =
|
||||
voice.gender === "male" ? "男声" : voice.gender === "female" ? "女声" : voice.gender
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`xx-clone-card${isPlaying ? " playing" : ""}${isFailed ? " failed" : ""}`}
|
||||
onClick={isFailed ? undefined : onShowDetail}
|
||||
>
|
||||
{/* 右上角操作按钮 */}
|
||||
<div className="xx-clone-card-actions">
|
||||
<Tooltip title="删除">
|
||||
<button
|
||||
@@ -77,38 +62,8 @@ const CloneVoiceCard: React.FC<CloneVoiceCardProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 头部:头像 + 名称 + 状态 */}
|
||||
<div className="xx-clone-card-header">
|
||||
<div className={`xx-clone-avatar${isProcessing ? " xx-clone-avatar--processing" : ""}`}>
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<div className="xx-clone-header-info">
|
||||
<h4 className="xx-clone-name" title={voice.name}>
|
||||
{voice.name}
|
||||
</h4>
|
||||
<span className={`xx-clone-status ${statusCfg.className}`}>
|
||||
<span className="xx-clone-status-dot" />
|
||||
{statusCfg.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<CardHeader voice={voice} />
|
||||
|
||||
{/* 描述 */}
|
||||
{voice.description && <p className="xx-clone-desc">{voice.description}</p>}
|
||||
|
||||
{/* 元信息 */}
|
||||
<div className="xx-clone-meta">
|
||||
{(voice.gender || voice.language) && (
|
||||
<span className="xx-clone-meta-item">
|
||||
<UserOutlined />
|
||||
{genderText}
|
||||
{voice.language ? ` · ${voice.language}` : ""}
|
||||
</span>
|
||||
)}
|
||||
<span className="xx-clone-meta-item">{voice.createdAt}</span>
|
||||
</div>
|
||||
|
||||
{/* 错误信息 */}
|
||||
{isFailed && voice.errorMessage && (
|
||||
<div className="xx-clone-error">
|
||||
<CloseCircleOutlined />
|
||||
@@ -116,63 +71,7 @@ const CloneVoiceCard: React.FC<CloneVoiceCardProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部操作区 */}
|
||||
<div className="xx-clone-footer">
|
||||
{voice.status === "ready" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-play-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
isPlaying ? onPause() : onPlay()
|
||||
}}
|
||||
title={isPlaying ? "暂停" : "试听"}
|
||||
>
|
||||
{isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
|
||||
</button>
|
||||
<div className="xx-clone-progress">
|
||||
<div
|
||||
className="xx-clone-progress-bar"
|
||||
style={{
|
||||
width: isPlaying
|
||||
? `${Math.min((currentTime / Math.max(voice.duration, 1)) * 100, 100)}%`
|
||||
: "0%",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-use-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onUse()
|
||||
}}
|
||||
>
|
||||
使用
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{isProcessing && (
|
||||
<div className="xx-clone-processing-hint">
|
||||
<ReloadOutlined spin />
|
||||
克隆处理中,请稍候...
|
||||
</div>
|
||||
)}
|
||||
{isFailed && (
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-retry-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onRetry()
|
||||
}}
|
||||
>
|
||||
<ReloadOutlined />
|
||||
重试克隆
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<CardFooter voice={voice} isPlaying={isPlaying} onRetry={onRetry} {...footerProps} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import React from "react"
|
||||
import { PlayCircleOutlined, PauseCircleOutlined, ReloadOutlined } from "@ant-design/icons"
|
||||
import { type ClonedVoiceDisplay } from "@/pages/voices/types"
|
||||
|
||||
interface CardFooterProps {
|
||||
voice: ClonedVoiceDisplay
|
||||
isPlaying: boolean
|
||||
currentTime: number
|
||||
onPlay: () => void
|
||||
onPause: () => void
|
||||
onUse: () => void
|
||||
onRetry: () => void
|
||||
}
|
||||
|
||||
const CardFooter: React.FC<CardFooterProps> = ({
|
||||
voice,
|
||||
isPlaying,
|
||||
currentTime,
|
||||
onPlay,
|
||||
onPause,
|
||||
onUse,
|
||||
onRetry,
|
||||
}) => {
|
||||
const isFailed = voice.status === "failed"
|
||||
const isProcessing = voice.status === "processing"
|
||||
|
||||
return (
|
||||
<div className="xx-clone-footer">
|
||||
{voice.status === "ready" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-play-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
isPlaying ? onPause() : onPlay()
|
||||
}}
|
||||
title={isPlaying ? "暂停" : "试听"}
|
||||
>
|
||||
{isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
|
||||
</button>
|
||||
<div className="xx-clone-progress">
|
||||
<div
|
||||
className="xx-clone-progress-bar"
|
||||
style={{
|
||||
width: isPlaying
|
||||
? `${Math.min((currentTime / Math.max(voice.duration, 1)) * 100, 100)}%`
|
||||
: "0%",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-use-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onUse()
|
||||
}}
|
||||
>
|
||||
使用
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{isProcessing && (
|
||||
<div className="xx-clone-processing-hint">
|
||||
<ReloadOutlined spin />
|
||||
克隆处理中,请稍候...
|
||||
</div>
|
||||
)}
|
||||
{isFailed && (
|
||||
<button
|
||||
type="button"
|
||||
className="xx-clone-retry-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onRetry()
|
||||
}}
|
||||
>
|
||||
<ReloadOutlined />
|
||||
重试克隆
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CardFooter
|
||||
@@ -0,0 +1,51 @@
|
||||
import React from "react"
|
||||
import { SoundOutlined, UserOutlined } from "@ant-design/icons"
|
||||
import { type ClonedVoiceDisplay } from "@/pages/voices/types"
|
||||
import { CLONE_STATUS_CONFIG } from "@/pages/voices/constants"
|
||||
|
||||
interface CardHeaderProps {
|
||||
voice: ClonedVoiceDisplay
|
||||
}
|
||||
|
||||
const genderTextOf = (gender: string) =>
|
||||
gender === "male" ? "男声" : gender === "female" ? "女声" : gender
|
||||
|
||||
const CardHeader: React.FC<CardHeaderProps> = ({ voice }) => {
|
||||
const statusCfg = CLONE_STATUS_CONFIG[voice.status]
|
||||
const isProcessing = voice.status === "processing"
|
||||
const genderText = genderTextOf(voice.gender ?? "")
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="xx-clone-card-header">
|
||||
<div className={`xx-clone-avatar${isProcessing ? " xx-clone-avatar--processing" : ""}`}>
|
||||
<SoundOutlined />
|
||||
</div>
|
||||
<div className="xx-clone-header-info">
|
||||
<h4 className="xx-clone-name" title={voice.name}>
|
||||
{voice.name}
|
||||
</h4>
|
||||
<span className={`xx-clone-status ${statusCfg.className}`}>
|
||||
<span className="xx-clone-status-dot" />
|
||||
{statusCfg.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{voice.description && <p className="xx-clone-desc">{voice.description}</p>}
|
||||
|
||||
<div className="xx-clone-meta">
|
||||
{(voice.gender || voice.language) && (
|
||||
<span className="xx-clone-meta-item">
|
||||
<UserOutlined />
|
||||
{genderText}
|
||||
{voice.language ? ` · ${voice.language}` : ""}
|
||||
</span>
|
||||
)}
|
||||
<span className="xx-clone-meta-item">{voice.createdAt}</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CardHeader
|
||||
@@ -6,8 +6,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
# ── 单轨时间计算 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -261,7 +259,6 @@ def db_to_linear(db: float) -> float:
|
||||
Returns:
|
||||
线性音量值
|
||||
"""
|
||||
import math
|
||||
|
||||
return 10 ** (db / 20.0)
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from packages.domain.pip_config import (
|
||||
ANIMATION_FADE,
|
||||
@@ -349,7 +348,7 @@ def build_pip_filters(
|
||||
input_args: list[str] = []
|
||||
current_label = base_label
|
||||
|
||||
for i, (layer, path) in enumerate(zip(layers, source_paths)):
|
||||
for i, (layer, path) in enumerate(zip(layers, source_paths, strict=False)):
|
||||
# 计算实际大小
|
||||
pip_w, pip_h = compute_pip_size(layer, output_width, output_height)
|
||||
|
||||
@@ -483,4 +482,4 @@ def count_visible_layers(layers: list[PiPLayerConfig]) -> int:
|
||||
|
||||
def sort_layers_by_z_index(layers: list[PiPLayerConfig]) -> list[PiPLayerConfig]:
|
||||
"""按 z_index 从小到大排序图层(z_index 小的先画,在底层)."""
|
||||
return sorted(layers, key=lambda l: l.z_index)
|
||||
return sorted(layers, key=lambda layer: layer.z_index)
|
||||
|
||||
@@ -13,12 +13,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from packages.domain.speed_config import (
|
||||
DEFAULT_SPEED,
|
||||
MAX_SPEED,
|
||||
MIN_SPEED,
|
||||
SpeedConfig,
|
||||
_split_atempo_stages,
|
||||
)
|
||||
|
||||
@@ -8,9 +8,10 @@ from packages.adapters.sqlalchemy_impl import (
|
||||
from packages.adapters.sqlalchemy_impl.schema_guard import assert_auto_create_schema_allowed
|
||||
|
||||
settings = get_settings()
|
||||
ensure_database_exists(settings.database_url)
|
||||
_db_url = settings.effective_database_url
|
||||
ensure_database_exists(_db_url)
|
||||
engine, SessionLocal = build_session_factory(
|
||||
settings.database_url,
|
||||
_db_url,
|
||||
pool_size=settings.database_pool_size,
|
||||
max_overflow=settings.database_max_overflow,
|
||||
pool_timeout=settings.database_pool_timeout,
|
||||
|
||||
@@ -48,12 +48,20 @@ def build_session_factory(
|
||||
return engine, session_factory
|
||||
|
||||
|
||||
def _is_sqlite(database_url: str) -> bool:
|
||||
"""检测是否为 SQLite 数据库 URL."""
|
||||
return database_url.startswith("sqlite")
|
||||
|
||||
|
||||
def _build_admin_url(database_url: str) -> URL:
|
||||
url = make_url(database_url)
|
||||
return url.set(database="postgres")
|
||||
|
||||
|
||||
def ensure_database_exists(database_url: str) -> None:
|
||||
"""确保数据库存在(仅 PostgreSQL 需要,SQLite 自动创建)."""
|
||||
if _is_sqlite(database_url):
|
||||
return
|
||||
target_url = make_url(database_url)
|
||||
admin_engine = create_engine(_build_admin_url(database_url), isolation_level="AUTOCOMMIT")
|
||||
try:
|
||||
@@ -70,6 +78,14 @@ def ensure_database_exists(database_url: str) -> None:
|
||||
|
||||
|
||||
def initialize_database(engine) -> None:
|
||||
"""初始化数据库 schema。
|
||||
|
||||
PostgreSQL 使用 advisory lock 防止并发初始化冲突;
|
||||
SQLite 直接 create_all(单文件,无并发风险)。
|
||||
"""
|
||||
if _is_sqlite(str(engine.url)):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
return
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT pg_advisory_lock(:lock_id)"), {"lock_id": SCHEMA_INIT_LOCK_ID})
|
||||
try:
|
||||
|
||||
@@ -34,6 +34,9 @@ class SharedSettings(BaseSettings):
|
||||
database_pool_timeout: int = 30
|
||||
database_pool_recycle: int = 3600
|
||||
|
||||
# 测试用:使用 SQLite 内存数据库(CI 环境无需 PostgreSQL)
|
||||
use_in_memory_db: bool = False
|
||||
|
||||
# ── Redis ────────────────────────────────────────────────────────────
|
||||
redis_url: str = "redis://localhost:6379/0"
|
||||
|
||||
@@ -66,6 +69,16 @@ class SharedSettings(BaseSettings):
|
||||
doubao_timeout: int = 30
|
||||
doubao_max_retries: int = 2
|
||||
|
||||
@property
|
||||
def effective_database_url(self) -> str:
|
||||
"""返回实际使用的数据库 URL。
|
||||
|
||||
当 USE_IN_MEMORY_DB=True 时返回 SQLite 内存 URL,否则返回 database_url。
|
||||
"""
|
||||
if self.use_in_memory_db:
|
||||
return "sqlite:///./test.db"
|
||||
return self.database_url
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
|
||||
@@ -22,22 +22,11 @@ import urllib.error
|
||||
import urllib.request
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from packages.domain.url_security import (
|
||||
ALLOWED_AUDIO_MIME_TYPES,
|
||||
ALLOWED_IMAGE_MIME_TYPES,
|
||||
)
|
||||
from packages.domain.url_security import ALLOWED_PORTS as _allowed_ports_base
|
||||
from packages.domain.url_security import ALLOWED_SCHEMES as _allowed_schemes_base
|
||||
from packages.domain.url_security import (
|
||||
ALLOWED_VIDEO_MIME_TYPES,
|
||||
MAGIC_NUMBERS,
|
||||
MAX_URL_LENGTH,
|
||||
)
|
||||
from packages.domain.url_security import UrlSecurityError as _UrlSecurityError_base
|
||||
from packages.domain.url_security import check_internal_hostname as _check_internal_hostname_base
|
||||
from packages.domain.url_security import check_ssrf_ip as _check_ssrf_ip_base
|
||||
from packages.domain.url_security import is_ip_address as _is_ip_address_base
|
||||
from packages.domain.url_security import is_trusted_domain as _is_trusted_domain_base
|
||||
from packages.domain.url_security import validate_magic_number as _validate_magic_number_base
|
||||
from packages.domain.url_security import validate_url_basic as _validate_url_basic_base
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
[pytest]
|
||||
pythonpath = . apps/api apps/worker packages
|
||||
testpaths = tests
|
||||
# importlib 模式避免同名测试文件的模块名冲突
|
||||
addopts = --import-mode=importlib
|
||||
|
||||
# ===== 覆盖率配置 =====
|
||||
# 覆盖率统计范围(供 --cov 使用时的默认源)
|
||||
|
||||
Executable
+567
@@ -0,0 +1,567 @@
|
||||
"""url_security 单测.
|
||||
|
||||
domain 层 URL 安全校验纯逻辑模块,0 网络依赖。
|
||||
覆盖 SSRF 防护、主机名校验、IP 检查、魔数校验等。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.url_security import (
|
||||
ALLOWED_IMAGE_MIME_TYPES,
|
||||
ALLOWED_PORTS,
|
||||
ALLOWED_SCHEMES,
|
||||
ALLOWED_VIDEO_MIME_TYPES,
|
||||
MAGIC_NUMBERS,
|
||||
MAX_URL_LENGTH,
|
||||
UrlSecurityError,
|
||||
check_internal_hostname,
|
||||
check_ssrf_ip,
|
||||
is_ip_address,
|
||||
is_trusted_domain,
|
||||
is_url_basic_safe,
|
||||
validate_magic_number,
|
||||
validate_url_basic,
|
||||
)
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# 常量与异常类
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""常量测试."""
|
||||
|
||||
def test_allowed_schemes(self):
|
||||
"""允许的 scheme 包含 http 和 https."""
|
||||
assert "http" in ALLOWED_SCHEMES
|
||||
assert "https" in ALLOWED_SCHEMES
|
||||
|
||||
def test_allowed_ports(self):
|
||||
"""允许的端口:80, 443."""
|
||||
assert 80 in ALLOWED_PORTS
|
||||
assert 443 in ALLOWED_PORTS
|
||||
|
||||
def test_max_url_length(self):
|
||||
"""最大 URL 长度 2048."""
|
||||
assert MAX_URL_LENGTH == 2048
|
||||
|
||||
def test_magic_numbers_has_common_formats(self):
|
||||
"""魔数表包含常见格式."""
|
||||
assert "image/jpeg" in MAGIC_NUMBERS
|
||||
assert "image/png" in MAGIC_NUMBERS
|
||||
assert "image/gif" in MAGIC_NUMBERS
|
||||
assert "video/mp4" in MAGIC_NUMBERS
|
||||
assert "audio/mpeg" in MAGIC_NUMBERS
|
||||
|
||||
|
||||
class TestUrlSecurityError:
|
||||
"""异常类测试."""
|
||||
|
||||
def test_is_value_error(self):
|
||||
"""UrlSecurityError 继承 ValueError."""
|
||||
assert issubclass(UrlSecurityError, ValueError)
|
||||
|
||||
def test_raise_with_message(self):
|
||||
"""抛出时携带错误信息."""
|
||||
with pytest.raises(UrlSecurityError, match="test error"):
|
||||
raise UrlSecurityError("test error")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# check_internal_hostname
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestCheckInternalHostname:
|
||||
"""内部主机名检查测试."""
|
||||
|
||||
def test_normal_domain_passes(self):
|
||||
"""普通外部域名通过."""
|
||||
check_internal_hostname("example.com")
|
||||
check_internal_hostname("www.google.com")
|
||||
|
||||
def test_localhost_blocked(self):
|
||||
"""localhost 被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="内部主机名"):
|
||||
check_internal_hostname("localhost")
|
||||
|
||||
def test_localhost_case_insensitive(self):
|
||||
"""大小写不敏感."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("LOCALHOST")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("LocalHost")
|
||||
|
||||
def test_localhost_localdomain_blocked(self):
|
||||
"""localhost.localdomain 被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("localhost.localdomain")
|
||||
|
||||
def test_metadata_blocked(self):
|
||||
"""metadata 被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("metadata")
|
||||
|
||||
def test_metadata_google_internal_blocked(self):
|
||||
"""GCP 元数据服务被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("metadata.google.internal")
|
||||
|
||||
def test_cloud_metadata_ip_blocked(self):
|
||||
"""云元数据 IP 169.254.169.254 被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("169.254.169.254")
|
||||
|
||||
def test_local_suffix_blocked(self):
|
||||
""".local 后缀域名被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="内网域名"):
|
||||
check_internal_hostname("myhost.local")
|
||||
|
||||
def test_internal_suffix_blocked(self):
|
||||
""".internal 后缀被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("svc.cluster.internal")
|
||||
|
||||
def test_localdomain_suffix_blocked(self):
|
||||
""".localdomain 后缀被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_internal_hostname("host.localdomain")
|
||||
|
||||
def test_com_domain_not_blocked(self):
|
||||
""".com 域名不被拦截."""
|
||||
check_internal_hostname("example.com")
|
||||
check_internal_hostname("sub.example.com")
|
||||
|
||||
def test_subdomain_of_public_domain_ok(self):
|
||||
"""公网域名的子域名正常."""
|
||||
check_internal_hostname("api.example.com")
|
||||
check_internal_hostname("cdn.assets.example.org")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# is_trusted_domain
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestIsTrustedDomain:
|
||||
"""可信域名匹配测试."""
|
||||
|
||||
def test_empty_trusted_domains_allows_all(self):
|
||||
"""空集合允许所有域名."""
|
||||
assert is_trusted_domain("anything.com", set()) is True
|
||||
assert is_trusted_domain("anywhere.org", set()) is True
|
||||
|
||||
def test_exact_match(self):
|
||||
"""精确匹配."""
|
||||
trusted = {"example.com", "example.org"}
|
||||
assert is_trusted_domain("example.com", trusted) is True
|
||||
assert is_trusted_domain("example.org", trusted) is True
|
||||
|
||||
def test_subdomain_match(self):
|
||||
"""子域名匹配."""
|
||||
trusted = {"example.com"}
|
||||
assert is_trusted_domain("api.example.com", trusted) is True
|
||||
assert is_trusted_domain("cdn.assets.example.com", trusted) is True
|
||||
|
||||
def test_no_match(self):
|
||||
"""不匹配."""
|
||||
trusted = {"example.com"}
|
||||
assert is_trusted_domain("other.com", trusted) is False
|
||||
assert is_trusted_domain("example.net", trusted) is False
|
||||
|
||||
def test_case_insensitive(self):
|
||||
"""大小写不敏感."""
|
||||
trusted = {"Example.COM"}
|
||||
assert is_trusted_domain("example.com", trusted) is True
|
||||
assert is_trusted_domain("API.EXAMPLE.COM", trusted) is True
|
||||
|
||||
def test_partial_match_no(self):
|
||||
"""域名部分相同但不是子域名不匹配."""
|
||||
trusted = {"example.com"}
|
||||
# fakeexample.com 不是 example.com 的子域名
|
||||
assert is_trusted_domain("fakeexample.com", trusted) is False
|
||||
|
||||
def test_none_trusted_domains(self):
|
||||
"""trusted_domains 为 None 时由调用方处理,空 set 全允许."""
|
||||
# 传空集合时全允许
|
||||
assert is_trusted_domain("a.com", set()) is True
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# check_ssrf_ip
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestCheckSsrIp:
|
||||
"""IP SSRF 检查测试."""
|
||||
|
||||
def test_public_ip_passes(self):
|
||||
"""公网 IP 通过."""
|
||||
check_ssrf_ip("8.8.8.8")
|
||||
check_ssrf_ip("1.1.1.1")
|
||||
check_ssrf_ip("114.114.114.114")
|
||||
|
||||
def test_loopback_blocked(self):
|
||||
"""回环地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="回环"):
|
||||
check_ssrf_ip("127.0.0.1")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("127.0.0.53")
|
||||
|
||||
def test_private_ip_blocked(self):
|
||||
"""私有内网 IP 被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="内网"):
|
||||
check_ssrf_ip("192.168.1.1")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("10.0.0.1")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("172.16.0.1")
|
||||
|
||||
def test_link_local_blocked(self):
|
||||
"""链路本地地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="链路本地"):
|
||||
check_ssrf_ip("169.254.169.254")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("169.254.1.1")
|
||||
|
||||
def test_multicast_blocked(self):
|
||||
"""组播地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="组播"):
|
||||
check_ssrf_ip("224.0.0.1")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("239.255.255.250")
|
||||
|
||||
def test_unspecified_blocked(self):
|
||||
"""未指定地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError, match="未指定"):
|
||||
check_ssrf_ip("0.0.0.0")
|
||||
|
||||
def test_ipv6_loopback_blocked(self):
|
||||
"""IPv6 回环地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("::1")
|
||||
|
||||
def test_ipv6_private_blocked(self):
|
||||
"""IPv6 内网地址被拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("fc00::1")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
check_ssrf_ip("fe80::1")
|
||||
|
||||
def test_ipv6_public_passes(self):
|
||||
"""IPv6 公网地址通过."""
|
||||
check_ssrf_ip("2001:4860:4860::8888")
|
||||
|
||||
def test_invalid_ip_raises_value_error(self):
|
||||
"""非法 IP 抛出 ValueError(不是 UrlSecurityError)."""
|
||||
with pytest.raises(ValueError):
|
||||
check_ssrf_ip("not-an-ip")
|
||||
with pytest.raises(ValueError):
|
||||
check_ssrf_ip("999.999.999.999")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# is_ip_address
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestIsIpAddress:
|
||||
"""IP 地址判断测试."""
|
||||
|
||||
def test_ipv4_true(self):
|
||||
"""IPv4 地址返回 True."""
|
||||
assert is_ip_address("127.0.0.1") is True
|
||||
assert is_ip_address("8.8.8.8") is True
|
||||
assert is_ip_address("0.0.0.0") is True
|
||||
|
||||
def test_ipv6_true(self):
|
||||
"""IPv6 地址返回 True."""
|
||||
assert is_ip_address("::1") is True
|
||||
assert is_ip_address("2001:db8::1") is True
|
||||
|
||||
def test_hostname_false(self):
|
||||
"""主机名返回 False."""
|
||||
assert is_ip_address("example.com") is False
|
||||
assert is_ip_address("localhost") is False
|
||||
assert is_ip_address("sub.domain.org") is False
|
||||
|
||||
def test_empty_string_false(self):
|
||||
"""空字符串返回 False."""
|
||||
assert is_ip_address("") is False
|
||||
|
||||
def test_invalid_ip_false(self):
|
||||
"""非法 IP 返回 False."""
|
||||
assert is_ip_address("999.999.999.999") is False
|
||||
assert is_ip_address("1234") is False
|
||||
assert is_ip_address("abc.def") is False
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# validate_url_basic
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestValidateUrlBasic:
|
||||
"""URL 基础校验测试."""
|
||||
|
||||
def test_normal_https_url_passes(self):
|
||||
"""正常 HTTPS URL 通过."""
|
||||
result = validate_url_basic("https://example.com/path")
|
||||
assert result == "https://example.com/path"
|
||||
|
||||
def test_normal_http_url_passes(self):
|
||||
"""正常 HTTP URL 通过."""
|
||||
result = validate_url_basic("http://example.com/path")
|
||||
assert result == "http://example.com/path"
|
||||
|
||||
def test_empty_url_rejected(self):
|
||||
"""空 URL 被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="为空"):
|
||||
validate_url_basic("")
|
||||
|
||||
def test_none_url_not_passed_as_str(self):
|
||||
"""None 作为 URL(这里只测空字符串)."""
|
||||
# 空字符串被拒
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("")
|
||||
|
||||
def test_too_long_url_rejected(self):
|
||||
"""超长 URL 被拒."""
|
||||
long_url = "https://example.com/" + "a" * 3000
|
||||
with pytest.raises(UrlSecurityError, match="过长"):
|
||||
validate_url_basic(long_url)
|
||||
|
||||
def test_invalid_scheme_rejected(self):
|
||||
"""非法 scheme 被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
validate_url_basic("ftp://example.com/file")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("file:///etc/passwd")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("javascript:alert(1)")
|
||||
|
||||
def test_missing_hostname_rejected(self):
|
||||
"""缺少主机名被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="主机名"):
|
||||
validate_url_basic("https:///path")
|
||||
|
||||
def test_localhost_rejected(self):
|
||||
"""localhost 被拒."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("https://localhost/api")
|
||||
|
||||
def test_internal_domain_rejected(self):
|
||||
"""内网域名被拒."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("http://server.local/api")
|
||||
|
||||
def test_non_standard_port_rejected(self):
|
||||
"""非标准端口被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="端口"):
|
||||
validate_url_basic("https://example.com:8080/")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("http://example.com:3000/")
|
||||
|
||||
def test_port_80_ok(self):
|
||||
"""80 端口允许."""
|
||||
validate_url_basic("http://example.com:80/path")
|
||||
|
||||
def test_port_443_ok(self):
|
||||
"""443 端口允许."""
|
||||
validate_url_basic("https://example.com:443/path")
|
||||
|
||||
def test_no_port_ok(self):
|
||||
"""无端口默认允许."""
|
||||
validate_url_basic("https://example.com/path")
|
||||
|
||||
def test_direct_ip_rejected_by_default(self):
|
||||
"""默认禁止直接 IP 访问."""
|
||||
with pytest.raises(UrlSecurityError, match="直接 IP"):
|
||||
validate_url_basic("https://8.8.8.8/path")
|
||||
|
||||
def test_direct_ip_allowed_when_enabled(self):
|
||||
"""allow_direct_ip=True 时允许公网 IP."""
|
||||
validate_url_basic("https://8.8.8.8/path", allow_direct_ip=True)
|
||||
|
||||
def test_direct_ip_private_still_blocked(self):
|
||||
"""即使 allow_direct_ip,内网 IP 仍被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="内网"):
|
||||
validate_url_basic("https://192.168.1.1/", allow_direct_ip=True)
|
||||
|
||||
def test_direct_ip_loopback_still_blocked(self):
|
||||
"""回环 IP 即使开启 direct_ip 也被拒."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("https://127.0.0.1/", allow_direct_ip=True)
|
||||
|
||||
def test_trusted_domains_pass(self):
|
||||
"""可信域名列表内的域名通过."""
|
||||
trusted = {"example.com", "cdn.com"}
|
||||
validate_url_basic("https://api.example.com/path", trusted_domains=trusted)
|
||||
validate_url_basic("https://cdn.com/asset.jpg", trusted_domains=trusted)
|
||||
|
||||
def test_untrusted_domain_rejected(self):
|
||||
"""不在可信域名列表中的域名被拒."""
|
||||
trusted = {"example.com"}
|
||||
with pytest.raises(UrlSecurityError, match="白名单"):
|
||||
validate_url_basic("https://evil.com/malware", trusted_domains=trusted)
|
||||
|
||||
def test_trusted_domain_subdomain_pass(self):
|
||||
"""可信域名的子域名通过."""
|
||||
trusted = {"example.com"}
|
||||
validate_url_basic("https://sub.example.com/a", trusted_domains=trusted)
|
||||
validate_url_basic("https://a.b.example.com/b", trusted_domains=trusted)
|
||||
|
||||
def test_return_value_is_original_url(self):
|
||||
"""返回原始 URL 字符串."""
|
||||
url = "https://example.com/path?query=value#frag"
|
||||
assert validate_url_basic(url) == url
|
||||
|
||||
def test_metadata_ip_rejected(self):
|
||||
"""云元数据 IP 被内部主机名检查拦截."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_basic("http://169.254.169.254/latest/meta-data/")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# is_url_basic_safe
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestIsUrlBasicSafe:
|
||||
"""便捷函数 is_url_basic_safe 测试."""
|
||||
|
||||
def test_safe_url_returns_true(self):
|
||||
"""安全 URL 返回 True."""
|
||||
assert is_url_basic_safe("https://example.com/") is True
|
||||
assert is_url_basic_safe("http://example.org/path") is True
|
||||
|
||||
def test_unsafe_url_returns_false(self):
|
||||
"""不安全 URL 返回 False."""
|
||||
assert is_url_basic_safe("https://localhost/") is False
|
||||
assert is_url_basic_safe("ftp://example.com/") is False
|
||||
assert is_url_basic_safe("") is False
|
||||
|
||||
def test_trusted_domains_param(self):
|
||||
"""支持 trusted_domains 参数."""
|
||||
trusted = {"example.com"}
|
||||
assert is_url_basic_safe("https://other.com/", trusted_domains=trusted) is False
|
||||
assert is_url_basic_safe("https://example.com/", trusted_domains=trusted) is True
|
||||
|
||||
def test_allow_direct_ip_param(self):
|
||||
"""支持 allow_direct_ip 参数."""
|
||||
assert is_url_basic_safe("https://8.8.8.8/") is False
|
||||
assert is_url_basic_safe("https://8.8.8.8/", allow_direct_ip=True) is True
|
||||
|
||||
def test_no_exceptions_raised(self):
|
||||
"""不抛出异常,只返回 bool."""
|
||||
# 各种边界情况都不抛异常
|
||||
try:
|
||||
is_url_basic_safe("")
|
||||
is_url_basic_safe("not a url")
|
||||
is_url_basic_safe("http://" + "a" * 3000)
|
||||
except UrlSecurityError:
|
||||
pytest.fail("is_url_basic_safe should not raise UrlSecurityError")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# validate_magic_number
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestValidateMagicNumber:
|
||||
"""魔数校验测试."""
|
||||
|
||||
def test_jpeg_valid(self):
|
||||
"""JPEG 文件通过."""
|
||||
# JPEG 文件头: FF D8 FF
|
||||
jpeg_header = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00"
|
||||
validate_magic_number(jpeg_header, {"image/jpeg"})
|
||||
|
||||
def test_png_valid(self):
|
||||
"""PNG 文件通过."""
|
||||
png_header = b"\x89PNG\r\n\x1a\n\x00\x00\x00"
|
||||
validate_magic_number(png_header, {"image/png"})
|
||||
|
||||
def test_gif_valid(self):
|
||||
"""GIF 文件通过(GIF89a 和 GIF87a)."""
|
||||
validate_magic_number(b"GIF89a...", {"image/gif"})
|
||||
validate_magic_number(b"GIF87a...", {"image/gif"})
|
||||
|
||||
def test_wav_valid(self):
|
||||
"""WAV 文件通过(RIFF + WAVE)."""
|
||||
wav_header = b"RIFF\x00\x00\x00\x00WAVEfmt "
|
||||
validate_magic_number(wav_header, {"audio/wav"})
|
||||
|
||||
def test_mp3_id3_valid(self):
|
||||
"""带 ID3 标签的 MP3 通过."""
|
||||
mp3_header = b"ID3\x03\x00\x00\x00\x00\x0f\x76"
|
||||
validate_magic_number(mp3_header, {"audio/mpeg"})
|
||||
|
||||
def test_mp3_sync_valid(self):
|
||||
"""不带 ID3 的 MP3(帧同步字)通过."""
|
||||
mp3_header = b"\xff\xfb\x90\x00" + b"\x00" * 32
|
||||
validate_magic_number(mp3_header, {"audio/mpeg"})
|
||||
|
||||
def test_ogg_valid(self):
|
||||
"""OGG 文件通过."""
|
||||
validate_magic_number(b"OggS\x00\x00...", {"audio/ogg"})
|
||||
|
||||
def test_flac_valid(self):
|
||||
"""FLAC 文件通过."""
|
||||
validate_magic_number(b"fLaC\x00\x00...", {"audio/flac"})
|
||||
|
||||
def test_webp_valid(self):
|
||||
"""WebP 文件通过(RIFF + WEBP)."""
|
||||
webp_header = b"RIFF\x00\x00\x00\x00WEBPVP8 "
|
||||
validate_magic_number(webp_header, {"image/webp"})
|
||||
|
||||
def test_bmp_valid(self):
|
||||
"""BMP 文件通过."""
|
||||
validate_magic_number(b"BM\x00\x00\x00\x00...", {"image/bmp"})
|
||||
|
||||
def test_mp4_valid(self):
|
||||
"""MP4 文件通过(ftyp 在偏移 4)."""
|
||||
mp4_header = b"\x00\x00\x00\x20ftypisom\x00\x00\x02\x00"
|
||||
validate_magic_number(mp4_header, {"video/mp4"})
|
||||
|
||||
def test_invalid_format_rejected(self):
|
||||
"""不匹配的格式被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="魔数"):
|
||||
validate_magic_number(b"hello world", {"image/jpeg"})
|
||||
|
||||
def test_empty_bytes_rejected(self):
|
||||
"""空字节被拒."""
|
||||
with pytest.raises(UrlSecurityError, match="为空"):
|
||||
validate_magic_number(b"", {"image/jpeg"})
|
||||
|
||||
def test_too_short_bytes_rejected(self):
|
||||
"""字节太短不匹配魔数时被拒."""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_magic_number(b"\xff\xd8", {"image/jpeg"}) # 只2字节,不够JPEG魔数
|
||||
|
||||
def test_multiple_allowed_types(self):
|
||||
"""允许多种格式时任一匹配即通过."""
|
||||
jpeg_header = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00"
|
||||
validate_magic_number(jpeg_header, {"image/jpeg", "image/png", "image/gif"})
|
||||
|
||||
def test_wrong_type_rejected(self):
|
||||
"""用 PNG 魔数校验 JPEG 类型失败."""
|
||||
jpeg_header = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00"
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_magic_number(jpeg_header, {"image/png"})
|
||||
|
||||
def test_unknown_mime_skipped(self):
|
||||
"""未知 MIME 类型(无对应魔数)不阻断."""
|
||||
# application/octet-stream 没有魔数定义,直接通过
|
||||
validate_magic_number(b"random bytes here", {"application/octet-stream"})
|
||||
|
||||
def test_allowed_image_mime_types_has_common(self):
|
||||
"""图片 MIME 白名单包含常见类型."""
|
||||
assert "image/jpeg" in ALLOWED_IMAGE_MIME_TYPES
|
||||
assert "image/png" in ALLOWED_IMAGE_MIME_TYPES
|
||||
|
||||
def test_allowed_video_mime_types_has_common(self):
|
||||
"""视频 MIME 白名单包含常见类型."""
|
||||
assert "video/mp4" in ALLOWED_VIDEO_MIME_TYPES
|
||||
@@ -5,6 +5,7 @@ domain 层纯逻辑模块,0 FFmpeg 依赖,快速轻量。
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -131,7 +132,7 @@ class TestClipFilterChain:
|
||||
def test_frozen(self):
|
||||
"""frozen dataclass 不可修改."""
|
||||
chain = _make_chain()
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(dataclasses.FrozenInstanceError):
|
||||
chain.duration = 10.0 # type: ignore
|
||||
|
||||
|
||||
|
||||
@@ -934,7 +934,7 @@ class TestSortLayersByZIndex:
|
||||
_make_layer(z_index=3, source="/tmp/c.mp4"),
|
||||
]
|
||||
sorted_layers = sort_layers_by_z_index(layers)
|
||||
assert [l.z_index for l in sorted_layers] == [1, 3, 5]
|
||||
assert [layer.z_index for layer in sorted_layers] == [1, 3, 5]
|
||||
|
||||
def test_same_z_index_stable(self):
|
||||
"""相同 z_index 保持相对顺序."""
|
||||
@@ -963,4 +963,4 @@ class TestSortLayersByZIndex:
|
||||
_make_layer(z_index=3, source="/tmp/3.mp4"),
|
||||
]
|
||||
sorted_layers = sort_layers_by_z_index(layers)
|
||||
assert [l.z_index for l in sorted_layers] == [-5, 0, 3]
|
||||
assert [layer.z_index for layer in sorted_layers] == [-5, 0, 3]
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.transition_presets import (
|
||||
@@ -57,7 +59,7 @@ class TestTransitionPreset:
|
||||
def test_frozen_immutable(self):
|
||||
"""frozen dataclass 不可修改."""
|
||||
p = TransitionPreset(id="t", name="T", category="basic")
|
||||
with pytest.raises(Exception): # FrozenInstanceError
|
||||
with pytest.raises(dataclasses.FrozenInstanceError):
|
||||
p.name = "新名字"
|
||||
|
||||
def test_not_hashable_due_to_list(self):
|
||||
|
||||
Reference in New Issue
Block a user