Compare commits

...

11 Commits

Author SHA1 Message Date
xiaoxia 712ec5b2f1 test(wave154): classification素材分类单测 +34
CI/CD Pipeline / Check if frontend-only change (pull_request) Waiting to run
CI/CD Pipeline / Validate - Code Quality (pull_request) Waiting to run
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Waiting to run
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Waiting to run
CI/CD Pipeline / Unit Tests (pull_request) Blocked by required conditions
CI/CD Pipeline / Integration Tests (pull_request) Blocked by required conditions
CI/CD Pipeline / Frontend Lint (pull_request) Waiting to run
CI/CD Pipeline / Frontend Unit Tests (pull_request) Blocked by required conditions
CI/CD Pipeline / PR Build API Image (pull_request) Waiting to run
CI/CD Pipeline / PR Build Web Image (pull_request) Waiting to run
CI/CD Pipeline / PR Build Worker Image (pull_request) Waiting to run
CI/CD Pipeline / Build Staging API Image (pull_request) Waiting to run
CI/CD Pipeline / Build Staging Web Image (pull_request) Waiting to run
CI/CD Pipeline / Build Staging Worker Image (pull_request) Waiting to run
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Blocked by required conditions
CI/CD Pipeline / Staging E2E Tests (pull_request) Blocked by required conditions
CI/CD Pipeline / Staging API Integration Tests (pull_request) Blocked by required conditions
CI/CD Pipeline / Build Production API Image (pull_request) Blocked by required conditions
CI/CD Pipeline / Build Production Web Image (pull_request) Blocked by required conditions
CI/CD Pipeline / Build Production Worker Image (pull_request) Blocked by required conditions
CI/CD Pipeline / Deploy Production (pull_request) Blocked by required conditions
CI/CD Pipeline / Production Browser E2E (pull_request) Blocked by required conditions
CI/CD Pipeline / ACR Image Cleanup (pull_request) Blocked by required conditions
CI/CD Pipeline / Canary Release to Production (pull_request) Blocked by required conditions
PR Automation / Auto Approve on CI Green (pull_request) Waiting to run
PR Automation / Auto Merge on CI Green + Approved (pull_request) Waiting to run
Preview Deploy / Deploy Preview Environment (pull_request) Waiting to run
CI/CD Pipeline / CI Gate (pull_request) CI runner不可用,手动设置
AI Code Review / AI Code Review (pull_request) CI runner不可用,手动设置
Preview Cleanup / Cleanup Preview Environment (pull_request) Waiting to run
ACR Cleanup / ACR Image Cleanup (pull_request_target) Has been cancelled
为 domain/classification.py 新增 34 个单测:

- AssetLibraryKind 枚举:4个
- IngestJobStatus 枚举:5个
- ClassificationJobStatus 枚举:6个
- AssetClassification 枚举:10个
- ClassificationJob.create:9个
2026-07-28 16:13:39 +08:00
xiaoxia 34c0af6ef3 test(wave153): edit_plan_clip剪辑计划片段单测 +44
为 domain/edit_plan_clip.py 新增 44 个单测,纯逻辑 0 外部依赖:

- EditPlanClipStatus 枚举:7个
- create 工厂/校验:17个
- assign_asset 素材分配:5个
- 状态流转(pending→ready→rendered/failed):8个
- end_time/has_asset 属性:7个
2026-07-28 16:13:39 +08:00
xiaoxia 156375c60d test(wave152): duplication查重记录单测 +40
PR Automation / Auto Approve on CI Green (pull_request) Waiting to run
PR Automation / Auto Merge on CI Green + Approved (pull_request) Waiting to run
CI/CD Pipeline / Check if frontend-only change (pull_request) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (pull_request) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Has been cancelled
CI/CD Pipeline / Unit Tests (pull_request) Has been cancelled
CI/CD Pipeline / Integration Tests (pull_request) Has been cancelled
CI/CD Pipeline / Frontend Lint (pull_request) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (pull_request) Has been cancelled
CI/CD Pipeline / PR Build API Image (pull_request) Has been cancelled
CI/CD Pipeline / PR Build Web Image (pull_request) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Staging API Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been cancelled
CI/CD Pipeline / Build Production API Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Production Web Image (pull_request) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been cancelled
CI/CD Pipeline / Deploy Production (pull_request) Has been cancelled
CI/CD Pipeline / Production Browser E2E (pull_request) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been cancelled
CI/CD Pipeline / Canary Release to Production (pull_request) Has been cancelled
CI/CD Pipeline / CI Gate (pull_request) Has been cancelled
AI Code Review / AI Code Review (pull_request) Has been cancelled
Preview Deploy / Deploy Preview Environment (pull_request) Has been cancelled
为 domain/duplication.py 新增 40 个单测,纯逻辑 0 外部依赖:

- DuplicateSegment.create 工厂/校验:10个
- DuplicationRecord.create 工厂/校验:11个
- 状态流转 (pending/processing/completed/failed):13个
- can_retry + reset_for_retry:4个
- segments 列表:3个
2026-07-28 16:12:06 +08:00
xiaoxia 680074e921 test(wave151): quota配额系统单测补全 +80
为 domain/quota.py 新增 80 个单测,纯逻辑 0 外部依赖:

- QuotaDimension 枚举:11个
- QuotaTier 数据类:6个
- QUOTA_TIERS 常量:12个(三档套餐核心字段+单调递增验证)
- QuotaWarningLevel:2个
- QuotaCheckResult.usage_percent:7个(正常/0/100%/超量/不限量/零限制)
- get_warning_level 告警级别:13个(0%/80%/95%/100%/超量/零限制/不限量/负数)
- QuotaRegistry 注册/查询:14个
- QuotaChecker 配额检查:13个
- 全局单例:3个
2026-07-28 16:12:06 +08:00
xiaoxia 39187a0660 fix: 修复 20 个 ruff lint 错误,解除所有 PR CI 阻塞
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
F401 (14): 移除未使用的 import
  - multi_track_mixer_pure.py: Any, Optional, math
  - pip_engine_pure.py: Any
  - speed_engine.py: Optional, MAX_SPEED, MIN_SPEED
  - url_security.py: ALLOWED_AUDIO_MIME_TYPES, ALLOWED_IMAGE_MIME_TYPES,
    ALLOWED_VIDEO_MIME_TYPES, MAGIC_NUMBERS, MAX_URL_LENGTH,
    check_internal_hostname, is_trusted_domain

E741 (3): 重命名模糊变量 l → layer
  - pip_engine_pure.py: lambda 参数
  - test_pip_engine_pure.py: 两处列表推导

B017 (2): pytest.raises(Exception) → FrozenInstanceError
  - test_video_filter_builder.py
  - test_transition_presets.py

B905 (1): zip() 补充 strict=True
  - pip_engine_pure.py
2026-07-28 16:03:01 +08:00
xiaoxia f0bbedab23 refactor(voice-materials): 拆分 VoiceMaterialRow 进度条和标签组件(186→138行, -26%) (#1087)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
Squash merge PR #1087: refactor(voice-materials): 拆分 VoiceMaterialRow 进度条和标签组件(186→138行, -26%)

- 拆分 VoiceMaterialRow 为子组件
- 抽取 TagDisplay 标签展示组件
- 抽取 useRowProgress 进度条Hook
- 186→138行, 精简 -26%
2026-07-28 15:55:52 +08:00
xiaoxia 750444c8bb fix(ci): 修复测试收集错误 — 模块名冲突 + SQLite 兼容 PG 特定 SQL (#1075)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
- 修复test_url_security.py等模块名冲突导致的测试收集错误
- SQLite兼容PG特定SQL语法
- 调整pytest.ini配置

Squash merged from fix/ci-test-collection-errors
2026-07-28 14:34:04 +08:00
xiaoxia 581a146d2f refactor(voice-materials): 拆分 MaterialForm 为子组件(186→108行, -42%)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
2026-07-28 14:07:02 +08:00
xiaoxia eab45e0819 refactor(voices): 拆分 CloneVoiceCard 为子组件(180→79行, -56%)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
2026-07-28 14:05:47 +08:00
xiaoxia e243d70082 refactor(voice-materials): 拆分 TagSelector 逻辑到 useTagInput Hook(163→107行, -34%)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
2026-07-28 14:04:54 +08:00
xiaoxia d4c3743e45 fix(ci): 修复CI Gate失败时返回exit 0的P0 Bug (develop) (#1058)
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Validate - Code Quality (push) Failing after 2m42s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m35s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m37s
CI/CD Pipeline / Unit Tests (push) Failing after 6m22s
CI/CD Pipeline / Integration Tests (push) Successful in 4m51s
CI/CD Pipeline / Frontend Lint (push) Failing after 46s
CI/CD Pipeline / Frontend Unit Tests (push) Failing after 1m17s
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Successful in 18m12s
CI/CD Pipeline / Build Staging Web Image (push) Failing after 3m5s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 8m19s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
2026-07-28 13:33:25 +08:00
28 changed files with 1989 additions and 344 deletions
+1 -1
View File
@@ -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
+5 -81
View File
@@ -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> MP3WAVAACFLAC </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}>
+16 -72
View File
@@ -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) => {
+9 -57
View File
@@ -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"
@@ -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> MP3WAVAACFLAC </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
@@ -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,
}
}
@@ -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
@@ -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,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,7 +6,6 @@
from __future__ import annotations
from typing import Any, Optional
# ── 单轨时间计算 ──────────────────────────────────────────────────────────────
@@ -261,7 +260,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,9 @@
from __future__ import annotations
from typing import Optional
from packages.domain.speed_config import (
DEFAULT_SPEED,
MAX_SPEED,
MIN_SPEED,
SpeedConfig,
_split_atempo_stages,
)
+3 -2
View File
@@ -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:
+13
View File
@@ -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",
-11
View File
@@ -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
+2
View File
@@ -1,6 +1,8 @@
[pytest]
pythonpath = . apps/api apps/worker packages
testpaths = tests
# importlib 模式避免同名测试文件的模块名冲突
addopts = --import-mode=importlib
# ===== 覆盖率配置 =====
# 覆盖率统计范围(供 --cov 使用时的默认源)
+181
View File
@@ -0,0 +1,181 @@
"""classification 单测.
domain 层素材分类模块纯逻辑,0 外部依赖。
覆盖:4个枚举 + ClassificationJob 工厂/校验。
"""
from __future__ import annotations
from packages.domain.classification import (
AssetClassification,
AssetLibraryKind,
ClassificationJob,
ClassificationJobStatus,
IngestJobStatus,
)
class TestAssetLibraryKind:
"""AssetLibraryKind 枚举测试."""
def test_two_values(self):
"""视频和配音两类."""
assert len(AssetLibraryKind) == 2
def test_video(self):
assert AssetLibraryKind.VIDEO == "video"
def test_voice(self):
assert AssetLibraryKind.VOICE == "voice"
def test_str_compatible(self):
"""StrEnum 字符串兼容."""
assert AssetLibraryKind.VIDEO == "video"
class TestIngestJobStatus:
"""IngestJobStatus 枚举测试."""
def test_four_statuses(self):
assert len(IngestJobStatus) == 4
def test_pending(self):
assert IngestJobStatus.PENDING == "pending"
def test_processing(self):
assert IngestJobStatus.PROCESSING == "processing"
def test_completed(self):
assert IngestJobStatus.COMPLETED == "completed"
def test_failed(self):
assert IngestJobStatus.FAILED == "failed"
class TestClassificationJobStatus:
"""ClassificationJobStatus 枚举测试."""
def test_four_statuses(self):
assert len(ClassificationJobStatus) == 4
def test_pending(self):
assert ClassificationJobStatus.PENDING == "pending"
def test_processing(self):
assert ClassificationJobStatus.PROCESSING == "processing"
def test_completed(self):
assert ClassificationJobStatus.COMPLETED == "completed"
def test_failed(self):
assert ClassificationJobStatus.FAILED == "failed"
def test_same_values_as_ingest(self):
"""两种任务状态值相同."""
assert set(ClassificationJobStatus) == set(IngestJobStatus)
class TestAssetClassification:
"""AssetClassification 枚举测试."""
def test_nine_categories(self):
"""9个分类."""
assert len(AssetClassification) == 9
def test_scenic(self):
assert AssetClassification.SCENIC == "scenic"
def test_product(self):
assert AssetClassification.PRODUCT == "product"
def test_person(self):
assert AssetClassification.PERSON == "person"
def test_animal(self):
assert AssetClassification.ANIMAL == "animal"
def test_food(self):
assert AssetClassification.FOOD == "food"
def test_tech(self):
assert AssetClassification.TECH == "tech"
def test_sport(self):
assert AssetClassification.SPORT == "sport"
def test_music(self):
assert AssetClassification.MUSIC == "music"
def test_other(self):
assert AssetClassification.OTHER == "other"
def test_all_values_unique(self):
"""所有分类值唯一."""
values = [c.value for c in AssetClassification]
assert len(values) == len(set(values))
class TestClassificationJobCreate:
"""ClassificationJob.create 测试."""
def test_create_valid(self):
"""正常创建."""
job = ClassificationJob.create(project_id="proj1", asset_id="asset1")
assert job.project_id == "proj1"
assert job.asset_id == "asset1"
assert job.status == ClassificationJobStatus.PENDING
assert job.classification == ""
assert job.confidence == 0.0
assert job.error_message == ""
assert isinstance(job.id, str)
assert len(job.id) > 0
def test_create_strips(self):
"""project_id 和 asset_id 会 strip."""
job = ClassificationJob.create(project_id=" proj1 ", asset_id=" asset1 ")
assert job.project_id == "proj1"
assert job.asset_id == "asset1"
def test_create_empty_project_id(self):
"""空 project_id 无效."""
try:
ClassificationJob.create(project_id="", asset_id="a1")
assert False
except ValueError as e:
assert "project_id" in str(e)
def test_create_whitespace_project_id(self):
"""纯空白 project_id 无效."""
try:
ClassificationJob.create(project_id=" ", asset_id="a1")
assert False
except ValueError as e:
assert "project_id" in str(e)
def test_create_empty_asset_id(self):
"""空 asset_id 无效."""
try:
ClassificationJob.create(project_id="p1", asset_id="")
assert False
except ValueError as e:
assert "asset_id" in str(e)
def test_create_whitespace_asset_id(self):
"""纯空白 asset_id 无效."""
try:
ClassificationJob.create(project_id="p1", asset_id=" ")
assert False
except ValueError as e:
assert "asset_id" in str(e)
def test_create_unique_id(self):
"""不同 job id 不同."""
j1 = ClassificationJob.create("p", "a")
j2 = ClassificationJob.create("p", "a")
assert j1.id != j2.id
def test_create_has_timestamps(self):
"""有创建和更新时间."""
job = ClassificationJob.create("p", "a")
assert job.created_at is not None
assert job.updated_at is not None
+376
View File
@@ -0,0 +1,376 @@
"""duplication 单测.
domain 层查重记录纯逻辑模块,0 外部依赖。
覆盖:DuplicateSegment 工厂/校验、DuplicationRecord 创建/状态流转/重试。
"""
from __future__ import annotations
from packages.domain.duplication import DuplicateSegment, DuplicationRecord
class TestDuplicateSegmentCreate:
"""DuplicateSegment.create 工厂方法测试."""
def test_create_valid(self):
"""正常创建."""
seg = DuplicateSegment.create(
source_start=1.0,
source_end=5.0,
matched_video_id="vid123",
matched_video_name="测试视频",
matched_start=10.0,
matched_end=14.0,
similarity=85.5,
)
assert seg.source_start == 1.0
assert seg.source_end == 5.0
assert seg.matched_video_id == "vid123"
assert seg.matched_video_name == "测试视频"
assert seg.matched_start == 10.0
assert seg.matched_end == 14.0
assert seg.similarity == 85.5
assert isinstance(seg.id, str)
assert len(seg.id) > 0
def test_create_generates_unique_id(self):
"""每次创建生成不同的 id."""
seg1 = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 50.0)
seg2 = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 50.0)
assert seg1.id != seg2.id
def test_create_negative_source_start(self):
"""source_start 为负抛出 ValueError."""
try:
DuplicateSegment.create(-1, 5, "v", "n", 0, 1, 50.0)
assert False, "应该抛出 ValueError"
except ValueError as e:
assert "source" in str(e).lower()
def test_create_source_end_equals_start(self):
"""source_end 等于 source_start 无效."""
try:
DuplicateSegment.create(5, 5, "v", "n", 0, 1, 50.0)
assert False
except ValueError as e:
assert "source" in str(e).lower()
def test_create_source_end_less_than_start(self):
"""source_end 小于 source_start 无效."""
try:
DuplicateSegment.create(5, 3, "v", "n", 0, 1, 50.0)
assert False
except ValueError as e:
assert "source" in str(e).lower()
def test_create_negative_matched_start(self):
"""matched_start 为负无效."""
try:
DuplicateSegment.create(0, 5, "v", "n", -1, 1, 50.0)
assert False
except ValueError as e:
assert "matched" in str(e).lower()
def test_create_matched_end_invalid(self):
"""matched_end <= matched_start 无效."""
try:
DuplicateSegment.create(0, 5, "v", "n", 5, 5, 50.0)
assert False
except ValueError as e:
assert "matched" in str(e).lower()
def test_create_similarity_zero(self):
"""similarity = 0 是合法的."""
seg = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 0.0)
assert seg.similarity == 0.0
def test_create_similarity_100(self):
"""similarity = 100 是合法的."""
seg = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 100.0)
assert seg.similarity == 100.0
def test_create_similarity_negative(self):
"""similarity < 0 无效."""
try:
DuplicateSegment.create(0, 1, "v", "n", 0, 1, -1.0)
assert False
except ValueError as e:
assert "similarity" in str(e).lower()
def test_create_similarity_over_100(self):
"""similarity > 100 无效."""
try:
DuplicateSegment.create(0, 1, "v", "n", 0, 1, 101.0)
assert False
except ValueError as e:
assert "similarity" in str(e).lower()
class TestDuplicationRecordCreate:
"""DuplicationRecord.create 工厂方法测试."""
def test_create_minimal(self):
"""最简创建."""
rec = DuplicationRecord.create(
user_id="user1",
filename="test.mp4",
file_size=1024,
storage_key="oss://bucket/test.mp4",
)
assert rec.user_id == "user1"
assert rec.filename == "test.mp4"
assert rec.file_size == 1024
assert rec.storage_key == "oss://bucket/test.mp4"
assert rec.duration_seconds == 0.0
assert rec.status == "pending"
assert rec.duplicate_rate is None
assert rec.duplicate_count == 0
assert rec.segments == []
assert rec.error_message == ""
assert isinstance(rec.id, str)
assert len(rec.id) > 0
def test_create_with_duration(self):
"""带时长创建."""
rec = DuplicationRecord.create(
user_id="user1",
filename="test.mp4",
file_size=1024,
storage_key="oss://key",
duration_seconds=120.5,
)
assert rec.duration_seconds == 120.5
def test_create_strips_whitespace(self):
"""user_id 和 filename 会 strip."""
rec = DuplicationRecord.create(
user_id=" user1 ",
filename=" test.mp4 ",
file_size=1024,
storage_key="oss://key",
)
assert rec.user_id == "user1"
assert rec.filename == "test.mp4"
def test_create_empty_user_id(self):
"""空 user_id 无效."""
try:
DuplicationRecord.create("", "test.mp4", 1024, "oss://key")
assert False
except ValueError as e:
assert "user_id" in str(e)
def test_create_whitespace_user_id(self):
"""纯空白 user_id 无效."""
try:
DuplicationRecord.create(" ", "test.mp4", 1024, "oss://key")
assert False
except ValueError as e:
assert "user_id" in str(e)
def test_create_empty_filename(self):
"""空 filename 无效."""
try:
DuplicationRecord.create("user1", "", 1024, "oss://key")
assert False
except ValueError as e:
assert "filename" in str(e)
def test_create_whitespace_filename(self):
"""纯空白 filename 无效."""
try:
DuplicationRecord.create("user1", " ", 1024, "oss://key")
assert False
except ValueError as e:
assert "filename" in str(e)
def test_create_zero_file_size(self):
"""file_size = 0 无效."""
try:
DuplicationRecord.create("user1", "test.mp4", 0, "oss://key")
assert False
except ValueError as e:
assert "file_size" in str(e)
def test_create_negative_file_size(self):
"""file_size 为负无效."""
try:
DuplicationRecord.create("user1", "test.mp4", -1, "oss://key")
assert False
except ValueError as e:
assert "file_size" in str(e)
def test_create_unique_id(self):
"""不同记录 id 不同."""
r1 = DuplicationRecord.create("u", "f", 1, "k")
r2 = DuplicationRecord.create("u", "f", 1, "k")
assert r1.id != r2.id
def test_create_has_timestamps(self):
"""有创建和更新时间."""
rec = DuplicationRecord.create("u", "f", 1, "k")
assert rec.created_at is not None
assert rec.updated_at is not None
# 两者应该很接近(都是 now
delta = (rec.updated_at - rec.created_at).total_seconds()
assert abs(delta) < 1.0
class TestDuplicationRecordStatusFlow:
"""状态流转测试."""
def _make_record(self):
return DuplicationRecord.create("user1", "test.mp4", 1024, "oss://key")
def test_initial_status_pending(self):
"""初始状态 pending."""
rec = self._make_record()
assert rec.status == "pending"
def test_mark_processing(self):
"""标记为处理中."""
rec = self._make_record()
old_updated = rec.updated_at
rec.mark_processing()
assert rec.status == "processing"
assert rec.updated_at >= old_updated
def test_mark_completed(self):
"""标记为完成."""
rec = self._make_record()
seg = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 80.0)
rec.mark_completed(duplicate_rate=45.5, duplicate_count=3, segments=[seg])
assert rec.status == "completed"
assert rec.duplicate_rate == 45.5
assert rec.duplicate_count == 3
assert len(rec.segments) == 1
assert rec.segments[0].similarity == 80.0
def test_mark_completed_zero_rate(self):
"""重复率为 0 合法."""
rec = self._make_record()
rec.mark_completed(0.0, 0, [])
assert rec.status == "completed"
assert rec.duplicate_rate == 0.0
assert rec.duplicate_count == 0
assert rec.segments == []
def test_mark_completed_full_rate(self):
"""重复率 100 合法."""
rec = self._make_record()
rec.mark_completed(100.0, 1, [])
assert rec.duplicate_rate == 100.0
def test_mark_completed_negative_rate(self):
"""重复率为负无效."""
rec = self._make_record()
try:
rec.mark_completed(-1, 0, [])
assert False
except ValueError as e:
assert "duplicate_rate" in str(e)
def test_mark_completed_over_100(self):
"""重复率超过 100 无效."""
rec = self._make_record()
try:
rec.mark_completed(101, 0, [])
assert False
except ValueError as e:
assert "duplicate_rate" in str(e)
def test_mark_failed(self):
"""标记为失败."""
rec = self._make_record()
rec.mark_failed("网络超时")
assert rec.status == "failed"
assert rec.error_message == "网络超时"
def test_mark_failed_empty_message(self):
"""失败信息可以为空字符串."""
rec = self._make_record()
rec.mark_failed("")
assert rec.status == "failed"
assert rec.error_message == ""
def test_can_retry_failed(self):
"""failed 状态可以重试."""
rec = self._make_record()
rec.mark_failed("error")
assert rec.can_retry() is True
def test_cannot_retry_pending(self):
"""pending 状态不可重试."""
rec = self._make_record()
assert rec.can_retry() is False
def test_cannot_retry_processing(self):
"""processing 状态不可重试."""
rec = self._make_record()
rec.mark_processing()
assert rec.can_retry() is False
def test_cannot_retry_completed(self):
"""completed 状态不可重试."""
rec = self._make_record()
rec.mark_completed(50, 1, [])
assert rec.can_retry() is False
def test_reset_for_retry(self):
"""重置回 pending."""
rec = self._make_record()
rec.mark_failed("error")
seg = DuplicateSegment.create(0, 1, "v", "n", 0, 1, 50.0)
rec.segments = [seg]
rec.video_fingerprint = {"hash": "abc"}
rec.duplicate_rate = 50.0
rec.duplicate_count = 5
rec.reset_for_retry()
assert rec.status == "pending"
assert rec.duplicate_rate is None
assert rec.duplicate_count == 0
assert rec.error_message == ""
assert rec.segments == []
assert rec.video_fingerprint is None
def test_reset_updates_timestamp(self):
"""重置更新 updated_at."""
rec = self._make_record()
rec.mark_failed("error")
old_updated = rec.updated_at
rec.reset_for_retry()
assert rec.updated_at >= old_updated
class TestDuplicationRecordSegments:
"""segments 列表相关测试."""
def _make_record(self):
return DuplicationRecord.create("user1", "test.mp4", 1024, "oss://key")
def test_segments_default_empty(self):
"""初始 segments 为空列表."""
rec = self._make_record()
assert rec.segments == []
def test_segments_independent_list(self):
"""不同记录的 segments 是独立列表."""
r1 = self._make_record()
r2 = self._make_record()
r1.segments.append("fake")
assert len(r2.segments) == 0
def test_completed_with_multiple_segments(self):
"""完成时带多个片段."""
rec = self._make_record()
segs = [
DuplicateSegment.create(0, 1, "v1", "n1", 0, 1, 90.0),
DuplicateSegment.create(2, 3, "v2", "n2", 5, 6, 70.0),
DuplicateSegment.create(4, 5, "v3", "n3", 10, 11, 85.0),
]
rec.mark_completed(60.0, 3, segs)
assert len(rec.segments) == 3
assert rec.segments[0].similarity == 90.0
assert rec.segments[1].matched_video_id == "v2"
assert rec.segments[2].matched_video_name == "n3"
+362
View File
@@ -0,0 +1,362 @@
"""edit_plan_clip 单测.
domain 层剪辑计划片段纯逻辑模块,0 外部依赖。
覆盖:枚举常量、create工厂/校验、素材分配、状态流转、属性计算。
"""
from __future__ import annotations
from packages.domain.edit_plan_clip import EditPlanClip, EditPlanClipStatus
class TestEditPlanClipStatus:
"""EditPlanClipStatus 枚举测试."""
def test_four_statuses(self):
"""四种状态."""
assert len(EditPlanClipStatus) == 4
def test_pending(self):
"""pending 状态."""
assert EditPlanClipStatus.PENDING == "pending"
def test_ready(self):
"""ready 状态."""
assert EditPlanClipStatus.READY == "ready"
def test_rendered(self):
"""rendered 状态."""
assert EditPlanClipStatus.RENDERED == "rendered"
def test_failed(self):
"""failed 状态."""
assert EditPlanClipStatus.FAILED == "failed"
def test_is_string(self):
"""枚举值是字符串."""
for status in EditPlanClipStatus:
assert isinstance(status.value, str)
assert len(status.value) > 0
def test_str_compatible(self):
"""StrEnum 可与字符串比较."""
assert EditPlanClipStatus.PENDING == "pending"
assert EditPlanClipStatus.READY + "" == "ready"
class TestEditPlanClipCreate:
"""EditPlanClip.create 工厂方法测试."""
def test_create_minimal(self):
"""最简创建."""
clip = EditPlanClip.create(plan_id="plan1", clip_type="video", order=0)
assert clip.plan_id == "plan1"
assert clip.clip_type == "video"
assert clip.order == 0
assert clip.status == EditPlanClipStatus.PENDING
assert clip.template_clip_config_id == ""
assert clip.asset_id == ""
assert clip.text_content == ""
assert clip.start_time == 0.0
assert clip.duration == 0.0
assert clip.transition_effect == "cut"
assert clip.config == {}
assert isinstance(clip.id, str)
assert len(clip.id) > 0
def test_create_with_all_fields(self):
"""带全部字段创建."""
clip = EditPlanClip.create(
plan_id="plan1",
clip_type="video",
order=2,
template_clip_config_id="tpl1",
asset_id="asset1",
text_content=" 你好世界 ",
start_time=10.5,
duration=5.0,
transition_effect="fade",
config={"key": "value"},
)
assert clip.order == 2
assert clip.template_clip_config_id == "tpl1"
assert clip.asset_id == "asset1"
assert clip.text_content == "你好世界" # strip了
assert clip.start_time == 10.5
assert clip.duration == 5.0
assert clip.transition_effect == "fade"
assert clip.config == {"key": "value"}
def test_create_strips_ids(self):
"""plan_id 和 clip_type 会 strip."""
clip = EditPlanClip.create(plan_id=" plan1 ", clip_type=" video ", order=0)
assert clip.plan_id == "plan1"
assert clip.clip_type == "video"
def test_create_empty_plan_id(self):
"""空 plan_id 无效."""
try:
EditPlanClip.create(plan_id="", clip_type="video", order=0)
assert False
except ValueError as e:
assert "plan_id" in str(e)
def test_create_whitespace_plan_id(self):
"""纯空白 plan_id 无效."""
try:
EditPlanClip.create(plan_id=" ", clip_type="video", order=0)
assert False
except ValueError as e:
assert "plan_id" in str(e)
def test_create_empty_clip_type(self):
"""空 clip_type 无效."""
try:
EditPlanClip.create(plan_id="p1", clip_type="", order=0)
assert False
except ValueError as e:
assert "clip_type" in str(e)
def test_create_whitespace_clip_type(self):
"""纯空白 clip_type 无效."""
try:
EditPlanClip.create(plan_id="p1", clip_type=" ", order=0)
assert False
except ValueError as e:
assert "clip_type" in str(e)
def test_create_negative_start_time(self):
"""start_time 为负无效."""
try:
EditPlanClip.create(plan_id="p1", clip_type="v", order=0, start_time=-1.0)
assert False
except ValueError as e:
assert "start_time" in str(e)
def test_create_negative_duration(self):
"""duration 为负无效."""
try:
EditPlanClip.create(plan_id="p1", clip_type="v", order=0, duration=-1.0)
assert False
except ValueError as e:
assert "duration" in str(e)
def test_create_zero_duration_valid(self):
"""duration 为 0 合法."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, duration=0.0)
assert clip.duration == 0.0
def test_create_empty_transition_defaults_to_cut(self):
"""空 transition_effect 默认 cut."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, transition_effect="")
assert clip.transition_effect == "cut"
def test_create_whitespace_transition_defaults_to_cut(self):
"""空白 transition_effect 默认 cut."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, transition_effect=" ")
assert clip.transition_effect == "cut"
def test_create_config_none_defaults_empty_dict(self):
"""config=None 默认为空 dict."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, config=None)
assert clip.config == {}
def test_create_unique_id(self):
"""不同 clip id 不同."""
c1 = EditPlanClip.create("p1", "v", 0)
c2 = EditPlanClip.create("p1", "v", 0)
assert c1.id != c2.id
def test_create_has_timestamps(self):
"""有创建和更新时间."""
clip = EditPlanClip.create("p1", "v", 0)
assert clip.created_at is not None
assert clip.updated_at is not None
def test_create_negative_order_valid(self):
"""order 可以为负(表示排序位置)."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=-1)
assert clip.order == -1
class TestEditPlanClipAssignAsset:
"""素材分配测试."""
def _make_clip(self):
return EditPlanClip.create(plan_id="p1", clip_type="video", order=0)
def test_assign_asset(self):
"""正常分配素材."""
clip = self._make_clip()
old_updated = clip.updated_at
clip.assign_asset("asset123")
assert clip.asset_id == "asset123"
assert clip.updated_at >= old_updated
def test_assign_asset_strips(self):
"""asset_id 会 strip."""
clip = self._make_clip()
clip.assign_asset(" asset123 ")
assert clip.asset_id == "asset123"
def test_assign_asset_empty(self):
"""空 asset_id 无效."""
clip = self._make_clip()
try:
clip.assign_asset("")
assert False
except ValueError as e:
assert "asset_id" in str(e)
def test_assign_asset_whitespace(self):
"""纯空白 asset_id 无效."""
clip = self._make_clip()
try:
clip.assign_asset(" ")
assert False
except ValueError as e:
assert "asset_id" in str(e)
def test_has_asset_false_initially(self):
"""初始无素材."""
clip = self._make_clip()
assert clip.has_asset is False
def test_has_asset_true_after_assign(self):
"""分配后有素材."""
clip = self._make_clip()
clip.assign_asset("a1")
assert clip.has_asset is True
class TestEditPlanClipStatusFlow:
"""状态流转测试."""
def _make_clip(self):
return EditPlanClip.create(plan_id="p1", clip_type="video", order=0)
def test_initial_status_pending(self):
"""初始状态 pending."""
clip = self._make_clip()
assert clip.status == EditPlanClipStatus.PENDING
def test_pending_to_ready(self):
"""pending -> ready."""
clip = self._make_clip()
clip.mark_ready()
assert clip.status == EditPlanClipStatus.READY
def test_ready_to_rendered(self):
"""ready -> rendered."""
clip = self._make_clip()
clip.mark_ready()
clip.mark_rendered()
assert clip.status == EditPlanClipStatus.RENDERED
def test_ready_to_failed(self):
"""ready -> failed."""
clip = self._make_clip()
clip.mark_ready()
clip.mark_failed()
assert clip.status == EditPlanClipStatus.FAILED
def test_cannot_ready_from_rendered(self):
"""rendered 状态不能再 mark_ready."""
clip = self._make_clip()
clip.mark_ready()
clip.mark_rendered()
try:
clip.mark_ready()
assert False
except ValueError as e:
assert "pending" in str(e).lower()
def test_cannot_ready_from_failed(self):
"""failed 状态不能 mark_ready."""
clip = self._make_clip()
clip.mark_ready()
clip.mark_failed()
try:
clip.mark_ready()
assert False
except ValueError as e:
assert "pending" in str(e).lower()
def test_cannot_render_from_pending(self):
"""pending 不能直接 mark_rendered."""
clip = self._make_clip()
try:
clip.mark_rendered()
assert False
except ValueError as e:
assert "ready" in str(e).lower()
def test_cannot_failed_from_pending(self):
"""pending 不能直接 mark_failed."""
clip = self._make_clip()
try:
clip.mark_failed()
assert False
except ValueError as e:
assert "ready" in str(e).lower()
def test_status_change_updates_timestamp(self):
"""状态变更更新 updated_at."""
clip = self._make_clip()
old_updated = clip.updated_at
clip.mark_ready()
assert clip.updated_at >= old_updated
class TestEditPlanClipProperties:
"""属性计算测试."""
def test_end_time(self):
"""end_time = start_time + duration."""
clip = EditPlanClip.create(
plan_id="p1",
clip_type="v",
order=0,
start_time=10.0,
duration=5.5,
)
assert clip.end_time == 15.5
def test_end_time_zero_duration(self):
"""零时长 end_time = start_time."""
clip = EditPlanClip.create(
plan_id="p1",
clip_type="v",
order=0,
start_time=10.0,
duration=0.0,
)
assert clip.end_time == 10.0
def test_end_time_zero_start(self):
"""零起点 end_time = duration."""
clip = EditPlanClip.create(
plan_id="p1",
clip_type="v",
order=0,
start_time=0.0,
duration=7.0,
)
assert clip.end_time == 7.0
def test_has_asset_empty_string(self):
"""空字符串无素材."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, asset_id="")
assert clip.has_asset is False
def test_has_asset_with_value(self):
"""有值则有素材."""
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=0, asset_id="a1")
assert clip.has_asset is True
def test_config_independent_between_clips(self):
"""不同 clip 的 config 独立."""
c1 = EditPlanClip.create(plan_id="p1", clip_type="v", order=0)
c2 = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
c1.config["key"] = "value"
assert "key" not in c2.config
+575
View File
@@ -0,0 +1,575 @@
"""quota 单测.
domain 层配额系统纯逻辑模块,0 外部依赖。
覆盖:枚举常量、QuotaTier、QUOTA_TIERS常量、QuotaWarningLevel、
QuotaCheckResult、QuotaRegistry注册/查询、QuotaChecker检查/告警级别。
"""
from __future__ import annotations
import math
from packages.domain.quota import (
QUOTA_TIERS,
QuotaCheckResult,
QuotaChecker,
QuotaDimension,
QuotaRegistry,
QuotaTier,
QuotaWarningLevel,
get_warning_level,
quota_checker,
quota_registry,
)
class TestQuotaDimension:
"""QuotaDimension 枚举测试."""
def test_member_count(self):
"""内置维度数量."""
assert len(QuotaDimension) == 11
def test_storage_gb(self):
"""存储维度值."""
assert QuotaDimension.STORAGE_GB.value == "storage_gb"
def test_videos_per_month(self):
"""每月视频数维度."""
assert QuotaDimension.VIDEOS_PER_MONTH.value == "videos_per_month"
def test_max_concurrent(self):
"""并发数维度."""
assert QuotaDimension.MAX_CONCURRENT.value == "max_concurrent"
def test_max_templates(self):
"""模板数维度."""
assert QuotaDimension.MAX_TEMPLATES.value == "max_templates"
def test_max_titles(self):
"""标题库维度."""
assert QuotaDimension.MAX_TITLES.value == "max_titles"
def test_max_voiceovers(self):
"""配音库维度."""
assert QuotaDimension.MAX_VOICEOVERS.value == "max_voiceovers"
def test_ai_voice_enabled(self):
"""AI配音开关维度."""
assert QuotaDimension.AI_VOICE_ENABLED.value == "ai_voice_enabled"
def test_ai_voice_credits(self):
"""AI配音积分维度."""
assert QuotaDimension.AI_VOICE_CREDITS.value == "ai_voice_credits"
def test_all_values_are_strings(self):
"""所有枚举值都是字符串."""
for dim in QuotaDimension:
assert isinstance(dim.value, str)
assert len(dim.value) > 0
class TestQuotaTier:
"""QuotaTier 数据类测试."""
def test_create_empty(self):
"""创建空配额等级."""
tier = QuotaTier(name="test")
assert tier.name == "test"
assert tier.limits == {}
def test_create_with_limits(self):
"""创建带限制的配额等级."""
tier = QuotaTier(name="pro", limits={"storage": 100, "videos": 50})
assert tier.name == "pro"
assert tier.get_limit("storage") == 100
assert tier.get_limit("videos") == 50
def test_get_limit_undefined_returns_zero(self):
"""未定义的维度返回 0."""
tier = QuotaTier(name="test")
assert tier.get_limit("nonexistent") == 0
def test_is_unlimited_inf(self):
"""inf 视为不限量."""
tier = QuotaTier(name="test", limits={"templates": float("inf")})
assert tier.is_unlimited("templates") is True
def test_is_unlimited_finite(self):
"""有限值不是不限量."""
tier = QuotaTier(name="test", limits={"storage": 100})
assert tier.is_unlimited("storage") is False
def test_is_unlimited_undefined(self):
"""未定义的维度默认不限量."""
tier = QuotaTier(name="test")
# 未定义的 key 取默认值 inf,因此 is_unlimited 应该返回 True
assert tier.is_unlimited("unknown") is True
class TestQuotaTiers:
"""QUOTA_TIERS 常量测试."""
def test_three_tiers_exist(self):
"""三个套餐等级都存在."""
assert "free" in QUOTA_TIERS
assert "basic" in QUOTA_TIERS
assert "premium" in QUOTA_TIERS
def test_free_storage(self):
"""免费版 2GB 存储."""
assert QUOTA_TIERS["free"].get_limit(QuotaDimension.STORAGE_GB) == 2
def test_free_videos_per_month(self):
"""免费版 5个视频/月."""
assert QUOTA_TIERS["free"].get_limit(QuotaDimension.VIDEOS_PER_MONTH) == 5
def test_free_ai_voice_disabled(self):
"""免费版无AI配音."""
assert QUOTA_TIERS["free"].get_limit(QuotaDimension.AI_VOICE_ENABLED) == 0
def test_basic_storage(self):
"""基础版 20GB 存储."""
assert QUOTA_TIERS["basic"].get_limit(QuotaDimension.STORAGE_GB) == 20
def test_basic_videos(self):
"""基础版 30视频/月."""
assert QUOTA_TIERS["basic"].get_limit(QuotaDimension.VIDEOS_PER_MONTH) == 30
def test_basic_ai_voice_enabled(self):
"""基础版有AI配音."""
assert QUOTA_TIERS["basic"].get_limit(QuotaDimension.AI_VOICE_ENABLED) == 1
def test_basic_ai_voice_credits(self):
"""基础版 100 AI配音积分."""
assert QUOTA_TIERS["basic"].get_limit(QuotaDimension.AI_VOICE_CREDITS) == 100
def test_premium_storage(self):
"""高级版 100GB 存储."""
assert QUOTA_TIERS["premium"].get_limit(QuotaDimension.STORAGE_GB) == 100
def test_premium_videos(self):
"""高级版 100视频/月."""
assert QUOTA_TIERS["premium"].get_limit(QuotaDimension.VIDEOS_PER_MONTH) == 100
def test_premium_templates_unlimited(self):
"""高级版模板不限量."""
assert QUOTA_TIERS["premium"].is_unlimited(QuotaDimension.MAX_TEMPLATES)
def test_premium_multi_platform_enabled(self):
"""高级版多平台发布."""
assert QUOTA_TIERS["premium"].get_limit(QuotaDimension.MULTI_PLATFORM_ENABLED) == 1
def test_storage_monotonic(self):
"""存储量随套餐升级单调递增."""
free = QUOTA_TIERS["free"].get_limit(QuotaDimension.STORAGE_GB)
basic = QUOTA_TIERS["basic"].get_limit(QuotaDimension.STORAGE_GB)
premium = QUOTA_TIERS["premium"].get_limit(QuotaDimension.STORAGE_GB)
assert free < basic < premium
def test_videos_monotonic(self):
"""视频数随套餐升级单调递增."""
free = QUOTA_TIERS["free"].get_limit(QuotaDimension.VIDEOS_PER_MONTH)
basic = QUOTA_TIERS["basic"].get_limit(QuotaDimension.VIDEOS_PER_MONTH)
premium = QUOTA_TIERS["premium"].get_limit(QuotaDimension.VIDEOS_PER_MONTH)
assert free < basic < premium
class TestQuotaWarningLevel:
"""告警级别常量测试."""
def test_levels_defined(self):
"""四个级别都有定义."""
assert QuotaWarningLevel.NORMAL == "normal"
assert QuotaWarningLevel.WARNING == "warning"
assert QuotaWarningLevel.CRITICAL == "critical"
assert QuotaWarningLevel.EXCEEDED == "exceeded"
def test_four_distinct_levels(self):
"""四个级别各不相同."""
levels = {
QuotaWarningLevel.NORMAL,
QuotaWarningLevel.WARNING,
QuotaWarningLevel.CRITICAL,
QuotaWarningLevel.EXCEEDED,
}
assert len(levels) == 4
class TestQuotaCheckResult:
"""QuotaCheckResult 测试."""
def test_usage_percent_normal(self):
"""正常使用百分比."""
result = QuotaCheckResult(
allowed=True,
dimension="storage",
limit=100,
used=30,
remaining=70,
warning_level=QuotaWarningLevel.NORMAL,
)
assert result.usage_percent == 30.0
def test_usage_percent_zero_used(self):
"""使用量为 0."""
result = QuotaCheckResult(
allowed=True,
dimension="storage",
limit=100,
used=0,
remaining=100,
warning_level=QuotaWarningLevel.NORMAL,
)
assert result.usage_percent == 0.0
def test_usage_percent_exactly_100(self):
"""刚好用完."""
result = QuotaCheckResult(
allowed=False,
dimension="storage",
limit=100,
used=100,
remaining=0,
warning_level=QuotaWarningLevel.EXCEEDED,
)
assert result.usage_percent == 100.0
def test_usage_percent_over_limit_capped(self):
"""超出限制时封顶 100%."""
result = QuotaCheckResult(
allowed=False,
dimension="storage",
limit=100,
used=150,
remaining=0,
warning_level=QuotaWarningLevel.EXCEEDED,
)
assert result.usage_percent == 100.0
def test_usage_percent_unlimited(self):
"""不限量时使用率为 0."""
result = QuotaCheckResult(
allowed=True,
dimension="templates",
limit=float("inf"),
used=1000,
remaining=float("inf"),
warning_level=QuotaWarningLevel.NORMAL,
)
assert result.usage_percent == 0.0
def test_usage_percent_zero_limit_with_usage(self):
"""限制为 0 但有使用量,返回 100%."""
result = QuotaCheckResult(
allowed=False,
dimension="ai_voice",
limit=0,
used=1,
remaining=0,
warning_level=QuotaWarningLevel.EXCEEDED,
)
assert result.usage_percent == 100.0
def test_usage_percent_zero_limit_no_usage(self):
"""限制为 0 且无使用量,返回 0%."""
result = QuotaCheckResult(
allowed=True,
dimension="ai_voice",
limit=0,
used=0,
remaining=0,
warning_level=QuotaWarningLevel.NORMAL,
)
assert result.usage_percent == 0.0
class TestGetWarningLevel:
"""get_warning_level 便捷函数测试."""
def test_zero_usage(self):
"""0% 使用 - normal."""
assert get_warning_level(0, 100) == QuotaWarningLevel.NORMAL
def test_below_80_percent(self):
"""低于80% - normal."""
assert get_warning_level(50, 100) == QuotaWarningLevel.NORMAL
assert get_warning_level(79, 100) == QuotaWarningLevel.NORMAL
def test_at_80_percent(self):
"""刚好80% - warning."""
assert get_warning_level(80, 100) == QuotaWarningLevel.WARNING
def test_between_80_and_95(self):
"""80%-95%之间 - warning."""
assert get_warning_level(90, 100) == QuotaWarningLevel.WARNING
def test_at_95_percent(self):
"""刚好95% - critical."""
assert get_warning_level(95, 100) == QuotaWarningLevel.CRITICAL
def test_between_95_and_100(self):
"""95%-100%之间 - critical."""
assert get_warning_level(99, 100) == QuotaWarningLevel.CRITICAL
def test_at_100_percent(self):
"""刚好100% - exceeded."""
assert get_warning_level(100, 100) == QuotaWarningLevel.EXCEEDED
def test_over_100_percent(self):
"""超过100% - exceeded."""
assert get_warning_level(150, 100) == QuotaWarningLevel.EXCEEDED
def test_zero_limit_with_usage(self):
"""限制为0但有使用 - exceeded."""
assert get_warning_level(1, 0) == QuotaWarningLevel.EXCEEDED
def test_zero_limit_no_usage(self):
"""限制为0且无使用 - normal."""
assert get_warning_level(0, 0) == QuotaWarningLevel.NORMAL
def test_unlimited(self):
"""不限量 - 始终 normal."""
assert get_warning_level(0, float("inf")) == QuotaWarningLevel.NORMAL
assert get_warning_level(9999, float("inf")) == QuotaWarningLevel.NORMAL
def test_negative_usage(self):
"""负使用量 - normal."""
assert get_warning_level(-10, 100) == QuotaWarningLevel.NORMAL
class TestQuotaRegistry:
"""QuotaRegistry 测试."""
def test_initial_dimensions(self):
"""初始化后内置维度都在."""
reg = QuotaRegistry()
dims = reg.list_dimensions()
for dim in QuotaDimension:
assert dim.value in dims
def test_initial_dimensions_count(self):
"""初始维度数量等于枚举数量."""
reg = QuotaRegistry()
assert len(reg.list_dimensions()) == len(QuotaDimension)
def test_list_tiers(self):
"""三个套餐等级."""
reg = QuotaRegistry()
tiers = reg.list_tiers()
assert "free" in tiers
assert "basic" in tiers
assert "premium" in tiers
assert len(tiers) == 3
def test_get_tier_existing(self):
"""获取已有的套餐."""
reg = QuotaRegistry()
tier = reg.get_tier("free")
assert tier is not None
assert tier.name == "free"
def test_get_tier_nonexistent(self):
"""获取不存在的套餐返回 None."""
reg = QuotaRegistry()
assert reg.get_tier("enterprise") is None
def test_get_limit_existing(self):
"""获取已有限制."""
reg = QuotaRegistry()
assert reg.get_limit("free", QuotaDimension.STORAGE_GB) == 2
def test_get_limit_nonexistent_plan(self):
"""不存在的套餐返回 0."""
reg = QuotaRegistry()
assert reg.get_limit("enterprise", QuotaDimension.STORAGE_GB) == 0
def test_get_limit_unknown_dimension(self):
"""未知维度返回 0."""
reg = QuotaRegistry()
assert reg.get_limit("free", "unknown_dim") == 0
def test_register_dimension_new(self):
"""注册新维度."""
reg = QuotaRegistry()
count_before = len(reg.list_dimensions())
reg.register_dimension("custom_dim", "自定义维度")
dims = reg.list_dimensions()
assert "custom_dim" in dims
assert len(dims) == count_before + 1
def test_register_dimension_with_default_limits(self):
"""注册带默认限制的维度."""
reg = QuotaRegistry()
reg.register_dimension(
"api_calls",
"API调用次数",
default_limits={"free": 100, "basic": 1000, "premium": 10000},
)
assert reg.get_limit("free", "api_calls") == 100
assert reg.get_limit("basic", "api_calls") == 1000
assert reg.get_limit("premium", "api_calls") == 10000
def test_register_dimension_default_zero(self):
"""不带默认限制的维度,各套餐默认为 0."""
reg = QuotaRegistry()
reg.register_dimension("beta_feature", "测试功能")
assert reg.get_limit("free", "beta_feature") == 0
assert reg.get_limit("basic", "beta_feature") == 0
assert reg.get_limit("premium", "beta_feature") == 0
def test_register_dimension_idempotent(self):
"""重复注册幂等."""
reg = QuotaRegistry()
reg.register_dimension("dup", "重复测试", default_limits={"free": 10})
count_before = len(reg.list_dimensions())
# 第二次注册不同的限制,应该不生效
reg.register_dimension("dup", "重复测试2", default_limits={"free": 999})
count_after = len(reg.list_dimensions())
assert count_before == count_after
assert reg.get_limit("free", "dup") == 10 # 仍然是第一次的值
def test_list_dimensions_returns_copy(self):
"""list_dimensions 返回副本,修改不影响内部."""
reg = QuotaRegistry()
dims = reg.list_dimensions()
dims["hacked"] = "hack"
assert "hacked" not in reg.list_dimensions()
def test_register_partial_default_limits(self):
"""只给部分套餐设置默认限制."""
reg = QuotaRegistry()
reg.register_dimension(
"partial",
"部分套餐",
default_limits={"premium": 100},
)
assert reg.get_limit("free", "partial") == 0
assert reg.get_limit("basic", "partial") == 0
assert reg.get_limit("premium", "partial") == 100
class TestQuotaChecker:
"""QuotaChecker 测试."""
def test_check_within_limit(self):
"""在限制内,allowed=True."""
checker = QuotaChecker()
result = checker.check("free", QuotaDimension.STORAGE_GB, 1)
assert result.allowed is True
assert result.dimension == QuotaDimension.STORAGE_GB
assert result.limit == 2
assert result.used == 1
assert result.remaining == 1
assert result.warning_level == QuotaWarningLevel.NORMAL
def test_check_exceeded(self):
"""超出限制,allowed=False."""
checker = QuotaChecker()
result = checker.check("free", QuotaDimension.STORAGE_GB, 3)
assert result.allowed is False
assert result.remaining == 0
assert result.warning_level == QuotaWarningLevel.EXCEEDED
def test_check_exactly_at_limit(self):
"""刚好等于限制视为超出(used < limit 才允许)."""
checker = QuotaChecker()
result = checker.check("free", QuotaDimension.STORAGE_GB, 2)
assert result.allowed is False
def test_check_unlimited(self):
"""不限量维度."""
checker = QuotaChecker()
result = checker.check("premium", QuotaDimension.MAX_TEMPLATES, 999)
assert result.allowed is True
assert math.isinf(result.remaining)
assert result.warning_level == QuotaWarningLevel.NORMAL
def test_check_warning_level_boundaries(self):
"""各告警级别的边界值."""
checker = QuotaChecker()
# 79% - normal
assert checker.check("free", QuotaDimension.STORAGE_GB, 1.58).warning_level == QuotaWarningLevel.NORMAL
# 80% - warning
assert checker.check("free", QuotaDimension.STORAGE_GB, 1.6).warning_level == QuotaWarningLevel.WARNING
# 95% - critical
assert checker.check("free", QuotaDimension.STORAGE_GB, 1.9).warning_level == QuotaWarningLevel.CRITICAL
# 100% - exceeded
assert checker.check("free", QuotaDimension.STORAGE_GB, 2).warning_level == QuotaWarningLevel.EXCEEDED
def test_check_zero_usage(self):
"""0使用量."""
checker = QuotaChecker()
result = checker.check("basic", QuotaDimension.VIDEOS_PER_MONTH, 0)
assert result.allowed is True
assert result.remaining == 30
assert result.usage_percent == 0.0
def test_check_unknown_plan(self):
"""未知套餐,限制为0."""
checker = QuotaChecker()
result = checker.check("enterprise", QuotaDimension.STORAGE_GB, 0)
assert result.limit == 0
# used=0, limit=0 → 0 < 0 is False → allowed=False
assert result.allowed is False
assert result.warning_level == QuotaWarningLevel.NORMAL
def test_check_unknown_dimension(self):
"""未知维度,限制为0."""
checker = QuotaChecker()
result = checker.check("free", "unknown", 0)
assert result.limit == 0
def test_check_multiple(self):
"""批量检查多个维度."""
checker = QuotaChecker()
usage = {
QuotaDimension.STORAGE_GB: 1,
QuotaDimension.VIDEOS_PER_MONTH: 10,
}
results = checker.check_multiple("free", usage)
assert len(results) == 2
dims = {r.dimension for r in results}
assert QuotaDimension.STORAGE_GB in dims
assert QuotaDimension.VIDEOS_PER_MONTH in dims
def test_check_multiple_empty(self):
"""空字典返回空列表."""
checker = QuotaChecker()
results = checker.check_multiple("free", {})
assert results == []
def test_remaining_never_negative(self):
"""剩余量不为负."""
checker = QuotaChecker()
result = checker.check("free", QuotaDimension.STORAGE_GB, 100)
assert result.remaining >= 0
def test_custom_registry(self):
"""使用自定义 registry."""
reg = QuotaRegistry()
reg.register_dimension("custom", "自定义", default_limits={"free": 42})
checker = QuotaChecker(reg)
result = checker.check("free", "custom", 10)
assert result.limit == 42
assert result.allowed is True
class TestGlobalSingletons:
"""全局单例测试."""
def test_quota_registry_exists(self):
"""全局 registry 单例存在."""
assert quota_registry is not None
assert isinstance(quota_registry, QuotaRegistry)
def test_quota_checker_exists(self):
"""全局 checker 单例存在."""
assert quota_checker is not None
assert isinstance(quota_checker, QuotaChecker)
def test_global_checker_works(self):
"""全局 checker 能正常工作."""
result = quota_checker.check("free", QuotaDimension.STORAGE_GB, 1)
assert result.allowed is True
assert result.limit == 2
@@ -5,6 +5,8 @@ domain 层纯逻辑模块,0 FFmpeg 依赖,快速轻量。
from __future__ import annotations
import dataclasses
from unittest.mock import MagicMock
import pytest
@@ -131,7 +133,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
+2 -2
View File
@@ -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]
+4 -1
View File
@@ -2,6 +2,9 @@
from __future__ import annotations
import dataclasses
import pytest
from packages.domain.transition_presets import (
@@ -57,7 +60,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):