From 000602a4c4b08f8e4681a832a82232a2a24f6533 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:32:37 +0800 Subject: [PATCH 1/9] =?UTF-8?q?test(wave151):=20quota=E9=85=8D=E9=A2=9D?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=8D=95=E6=B5=8B=E8=A1=A5=E5=85=A8=20+80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 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个 --- tests/unit/domain/test_quota.py | 575 ++++++++++++++++++++++++++++++++ 1 file changed, 575 insertions(+) create mode 100755 tests/unit/domain/test_quota.py diff --git a/tests/unit/domain/test_quota.py b/tests/unit/domain/test_quota.py new file mode 100755 index 000000000..36d578627 --- /dev/null +++ b/tests/unit/domain/test_quota.py @@ -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 -- 2.54.0 From 76043aeeccf3159ac3b3d7585492a6b646fc27ce Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:35:04 +0800 Subject: [PATCH 2/9] =?UTF-8?q?test(wave152):=20duplication=E6=9F=A5?= =?UTF-8?q?=E9=87=8D=E8=AE=B0=E5=BD=95=E5=8D=95=E6=B5=8B=20+40?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/duplication.py 新增 40 个单测,纯逻辑 0 外部依赖: - DuplicateSegment.create 工厂/校验:10个 - DuplicationRecord.create 工厂/校验:11个 - 状态流转 (pending/processing/completed/failed):13个 - can_retry + reset_for_retry:4个 - segments 列表:3个 --- tests/unit/domain/test_duplication.py | 376 ++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 tests/unit/domain/test_duplication.py diff --git a/tests/unit/domain/test_duplication.py b/tests/unit/domain/test_duplication.py new file mode 100644 index 000000000..884bcbd0b --- /dev/null +++ b/tests/unit/domain/test_duplication.py @@ -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" -- 2.54.0 From 3540f154804aeaad6ac3930b211493486dfe25ea Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:37:32 +0800 Subject: [PATCH 3/9] =?UTF-8?q?test(wave153):=20edit=5Fplan=5Fclip?= =?UTF-8?q?=E5=89=AA=E8=BE=91=E8=AE=A1=E5=88=92=E7=89=87=E6=AE=B5=E5=8D=95?= =?UTF-8?q?=E6=B5=8B=20+44?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/edit_plan_clip.py 新增 44 个单测,纯逻辑 0 外部依赖: - EditPlanClipStatus 枚举:7个 - create 工厂/校验:17个 - assign_asset 素材分配:5个 - 状态流转(pending→ready→rendered/failed):8个 - end_time/has_asset 属性:7个 --- tests/unit/domain/test_edit_plan_clip.py | 362 +++++++++++++++++++++++ 1 file changed, 362 insertions(+) create mode 100644 tests/unit/domain/test_edit_plan_clip.py diff --git a/tests/unit/domain/test_edit_plan_clip.py b/tests/unit/domain/test_edit_plan_clip.py new file mode 100644 index 000000000..e1361cdd2 --- /dev/null +++ b/tests/unit/domain/test_edit_plan_clip.py @@ -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 -- 2.54.0 From 04fe9a55c59bdb431b348bee943cffad826ed126 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:39:24 +0800 Subject: [PATCH 4/9] =?UTF-8?q?test(wave154):=20classification=E7=B4=A0?= =?UTF-8?q?=E6=9D=90=E5=88=86=E7=B1=BB=E5=8D=95=E6=B5=8B=20+34?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/classification.py 新增 34 个单测: - AssetLibraryKind 枚举:4个 - IngestJobStatus 枚举:5个 - ClassificationJobStatus 枚举:6个 - AssetClassification 枚举:10个 - ClassificationJob.create:9个 --- tests/unit/domain/test_classification.py | 181 +++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 tests/unit/domain/test_classification.py diff --git a/tests/unit/domain/test_classification.py b/tests/unit/domain/test_classification.py new file mode 100644 index 000000000..09077950a --- /dev/null +++ b/tests/unit/domain/test_classification.py @@ -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 -- 2.54.0 From 72e8d59f5dd030b439e2bfe19e15120b8e15a5ad Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:41:19 +0800 Subject: [PATCH 5/9] =?UTF-8?q?test(wave155):=20generated=5Fvideo=E7=94=9F?= =?UTF-8?q?=E6=88=90=E8=A7=86=E9=A2=91=E5=AE=9E=E4=BD=93=E5=8D=95=E6=B5=8B?= =?UTF-8?q?=20+16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/generated_video.py 新增 16 个单测: - create 必填字段 + 默认值 - strip 行为 - 4个空值校验(project_id/task_id/name/file_url) - 唯一ID + 时间戳 - 零值合法(宽高/fps) - generation_params 独立性 --- tests/unit/domain/test_generated_video.py | 170 ++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 tests/unit/domain/test_generated_video.py diff --git a/tests/unit/domain/test_generated_video.py b/tests/unit/domain/test_generated_video.py new file mode 100644 index 000000000..c5259e5af --- /dev/null +++ b/tests/unit/domain/test_generated_video.py @@ -0,0 +1,170 @@ +"""generated_video 单测. + +domain 层生成视频实体纯逻辑模块,0 外部依赖。 +覆盖:create工厂/校验、默认值、数据完整性。 +""" + +from __future__ import annotations + +from packages.domain.generated_video import GeneratedVideo + + +class TestGeneratedVideoCreate: + """GeneratedVideo.create 工厂测试.""" + + def test_create_required_fields(self): + """最简创建(仅必填字段).""" + v = GeneratedVideo.create( + project_id="proj1", + generation_task_id="task1", + name="我的视频", + file_url="https://cdn.example.com/v.mp4", + ) + assert v.project_id == "proj1" + assert v.generation_task_id == "task1" + assert v.name == "我的视频" + assert v.file_url == "https://cdn.example.com/v.mp4" + assert isinstance(v.id, str) + assert len(v.id) > 0 + + def test_create_defaults(self): + """默认值正确.""" + v = GeneratedVideo.create( + project_id="p1", + generation_task_id="t1", + name="v", + file_url="http://x/v.mp4", + ) + assert v.file_size == 0 + assert v.duration == 0.0 + assert v.width == 0 + assert v.height == 0 + assert v.fps == 0.0 + assert v.thumbnail_url is None + assert v.status == "completed" + assert v.review_status == "pending_review" + assert v.generation_params == {} + assert v.video_fingerprint is None + assert v.is_duplicate is False + assert v.duplicate_of is None + + def test_create_with_all_fields(self): + """带全部字段创建.""" + v = GeneratedVideo.create( + project_id="proj1", + generation_task_id="task1", + name=" 测试视频 ", + file_url=" https://cdn.example.com/v.mp4 ", + file_size=1024000, + duration=120.5, + width=1920, + height=1080, + fps=30.0, + thumbnail_url="https://cdn.example.com/thumb.jpg", + generation_params={"template": "tpl1", "bgm": "bgm1"}, + ) + assert v.name == "测试视频" # strip + assert v.file_url == "https://cdn.example.com/v.mp4" # strip + assert v.file_size == 1024000 + assert v.duration == 120.5 + assert v.width == 1920 + assert v.height == 1080 + assert v.fps == 30.0 + assert v.thumbnail_url == "https://cdn.example.com/thumb.jpg" + assert v.generation_params == {"template": "tpl1", "bgm": "bgm1"} + + def test_create_strips_fields(self): + """字符串字段会 strip.""" + v = GeneratedVideo.create( + project_id=" p1 ", + generation_task_id=" t1 ", + name=" v ", + file_url=" http://x/v ", + ) + assert v.project_id == "p1" + assert v.generation_task_id == "t1" + assert v.name == "v" + assert v.file_url == "http://x/v" + + def test_create_empty_project_id(self): + """空 project_id 无效.""" + try: + GeneratedVideo.create("", "t1", "v", "http://x/v") + assert False + except ValueError as e: + assert "project_id" in str(e) + + def test_create_whitespace_project_id(self): + """纯空白 project_id 无效.""" + try: + GeneratedVideo.create(" ", "t1", "v", "http://x/v") + assert False + except ValueError as e: + assert "project_id" in str(e) + + def test_create_empty_task_id(self): + """空 generation_task_id 无效.""" + try: + GeneratedVideo.create("p1", "", "v", "http://x/v") + assert False + except ValueError as e: + assert "generation_task_id" in str(e) + + def test_create_empty_name(self): + """空 name 无效.""" + try: + GeneratedVideo.create("p1", "t1", "", "http://x/v") + assert False + except ValueError as e: + assert "name" in str(e) + + def test_create_empty_file_url(self): + """空 file_url 无效.""" + try: + GeneratedVideo.create("p1", "t1", "v", "") + assert False + except ValueError as e: + assert "file_url" in str(e) + + def test_create_whitespace_file_url(self): + """纯空白 file_url 无效.""" + try: + GeneratedVideo.create("p1", "t1", "v", " ") + assert False + except ValueError as e: + assert "file_url" in str(e) + + def test_create_generation_params_none_defaults_empty(self): + """generation_params=None 默认为空 dict.""" + v = GeneratedVideo.create("p1", "t1", "v", "http://x/v", generation_params=None) + assert v.generation_params == {} + + def test_create_unique_id(self): + """不同视频 id 不同.""" + v1 = GeneratedVideo.create("p", "t", "v", "http://x/v") + v2 = GeneratedVideo.create("p", "t", "v", "http://x/v") + assert v1.id != v2.id + + def test_create_has_timestamps(self): + """有生成和创建时间.""" + v = GeneratedVideo.create("p", "t", "v", "http://x/v") + assert v.generated_at is not None + assert v.created_at is not None + + def test_zero_dimensions_valid(self): + """宽高为 0 合法(未指定分辨率).""" + v = GeneratedVideo.create("p", "t", "v", "http://x/v", width=0, height=0) + assert v.width == 0 + assert v.height == 0 + + def test_zero_fps_valid(self): + """fps 为 0 合法.""" + v = GeneratedVideo.create("p", "t", "v", "http://x/v", fps=0.0) + assert v.fps == 0.0 + + def test_generation_params_independent(self): + """不同实例的 generation_params 独立.""" + v1 = GeneratedVideo.create("p", "t", "v", "http://x/v") + v2 = GeneratedVideo.create("p", "t", "v", "http://x/v") + v1.generation_params["key"] = "value" + assert "key" not in v2.generation_params -- 2.54.0 From aedbe051400cb2b79d1b3bd38a21cc2d667024ab Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:43:16 +0800 Subject: [PATCH 6/9] =?UTF-8?q?test(wave156):=20generation=5Ftask=E7=94=9F?= =?UTF-8?q?=E6=88=90=E4=BB=BB=E5=8A=A1=E5=AE=9E=E4=BD=93=E5=8D=95=E6=B5=8B?= =?UTF-8?q?=20+24?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/generation_task.py 新增 24 个单测: - GenerationTaskStatus 枚举:6个 - create 工厂:18个(最简/全字段/二选一校验/列表拷贝/默认值) --- tests/unit/domain/test_generation_task.py | 208 ++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 tests/unit/domain/test_generation_task.py diff --git a/tests/unit/domain/test_generation_task.py b/tests/unit/domain/test_generation_task.py new file mode 100644 index 000000000..edca75f5c --- /dev/null +++ b/tests/unit/domain/test_generation_task.py @@ -0,0 +1,208 @@ +"""generation_task 单测. + +domain 层生成任务实体纯逻辑模块,0 外部依赖。 +覆盖:枚举、create工厂/校验、列表拷贝。 +""" + +from __future__ import annotations + +from packages.domain.generation_task import GenerationTask, GenerationTaskStatus + + +class TestGenerationTaskStatus: + """GenerationTaskStatus 枚举测试.""" + + def test_five_statuses(self): + """五种状态.""" + assert len(GenerationTaskStatus) == 5 + + def test_pending(self): + assert GenerationTaskStatus.PENDING == "pending" + + def test_running(self): + assert GenerationTaskStatus.RUNNING == "running" + + def test_completed(self): + assert GenerationTaskStatus.COMPLETED == "completed" + + def test_failed(self): + assert GenerationTaskStatus.FAILED == "failed" + + def test_cancelled(self): + assert GenerationTaskStatus.CANCELLED == "cancelled" + + +class TestGenerationTaskCreate: + """GenerationTask.create 工厂测试.""" + + def test_create_minimal(self): + """最简创建(project_id + asset_library_id).""" + task = GenerationTask.create(project_id="proj1", asset_library_id="lib1") + assert task.project_id == "proj1" + assert task.asset_library_id == "lib1" + assert task.status == GenerationTaskStatus.PENDING + assert task.progress == 0.0 + assert task.result_count == 0 + assert task.error_message == "" + assert task.asset_ids == [] + assert task.title_ids == [] + assert task.voice_ids == [] + assert isinstance(task.id, str) + assert len(task.id) > 0 + + def test_create_with_all_fields(self): + """带全部字段创建.""" + task = GenerationTask.create( + project_id=" proj1 ", + asset_library_id=" lib1 ", + strategy_id=" strat1 ", + voice_library_id=" vlib1 ", + template_id=" tpl1 ", + asset_ids=["a1", "a2", "a3"], + title_ids=["t1", "t2"], + voice_ids=["v1"], + created_by_user_id=" user1 ", + source_edit_plan_id=" plan1 ", + asset_select_mode="random", + batch_id="batch1", + ) + assert task.project_id == "proj1" + assert task.asset_library_id == "lib1" + assert task.strategy_id == "strat1" + assert task.voice_library_id == "vlib1" + assert task.template_id == "tpl1" + assert task.asset_ids == ["a1", "a2", "a3"] + assert task.title_ids == ["t1", "t2"] + assert task.voice_ids == ["v1"] + assert task.created_by_user_id == "user1" + assert task.source_edit_plan_id == "plan1" + assert task.asset_select_mode == "random" + assert task.batch_id == "batch1" + + def test_create_with_template_instead_of_project(self): + """有 template_id 但 project_id 为空也可以.""" + task = GenerationTask.create( + project_id="", + asset_library_id="lib1", + template_id="tpl1", + ) + assert task.template_id == "tpl1" + assert task.project_id == "" + + def test_create_neither_project_nor_template(self): + """project_id 和 template_id 都为空,抛错.""" + try: + GenerationTask.create(project_id="", asset_library_id="lib1") + assert False + except ValueError as e: + assert "project_id" in str(e) and "template_id" in str(e) + + def test_create_whitespace_project_and_template(self): + """都是空白也抛错.""" + try: + GenerationTask.create(project_id=" ", asset_library_id="lib1", template_id=" ") + assert False + except ValueError as e: + assert "project_id" in str(e) and "template_id" in str(e) + + def test_create_no_asset_library_and_no_ids(self): + """asset_library_id 为空且没有素材列表,抛错.""" + try: + GenerationTask.create(project_id="p1", asset_library_id="") + assert False + except ValueError as e: + assert "asset_library_id" in str(e) + + def test_create_whitespace_asset_library_and_no_ids(self): + """空白 asset_library 且无素材列表,抛错.""" + try: + GenerationTask.create(project_id="p1", asset_library_id=" ") + assert False + except ValueError as e: + assert "asset_library_id" in str(e) + + def test_create_with_asset_ids_instead_of_library(self): + """用 asset_ids 替代 asset_library_id.""" + task = GenerationTask.create( + project_id="p1", + asset_library_id="", + asset_ids=["a1", "a2"], + ) + assert task.asset_library_id == "" + assert task.asset_ids == ["a1", "a2"] + + def test_create_with_title_ids_instead_of_library(self): + """用 title_ids 替代 asset_library_id.""" + task = GenerationTask.create( + project_id="p1", + asset_library_id="", + title_ids=["t1"], + ) + assert task.title_ids == ["t1"] + + def test_create_with_voice_ids_instead_of_library(self): + """用 voice_ids 替代 asset_library_id.""" + task = GenerationTask.create( + project_id="p1", + asset_library_id="", + voice_ids=["v1"], + ) + assert task.voice_ids == ["v1"] + + def test_create_asset_ids_copied(self): + """asset_ids 是拷贝不是引用.""" + original = ["a1", "a2"] + task = GenerationTask.create(project_id="p1", asset_library_id="lib1", asset_ids=original) + original.append("a3") + assert task.asset_ids == ["a1", "a2"] + + def test_create_title_ids_copied(self): + """title_ids 是拷贝不是引用.""" + original = ["t1"] + task = GenerationTask.create(project_id="p1", asset_library_id="lib1", title_ids=original) + original.append("t2") + assert task.title_ids == ["t1"] + + def test_create_voice_ids_copied(self): + """voice_ids 是拷贝不是引用.""" + original = ["v1"] + task = GenerationTask.create(project_id="p1", asset_library_id="lib1", voice_ids=original) + original.append("v2") + assert task.voice_ids == ["v1"] + + def test_create_none_lists_default_empty(self): + """None 列表默认为空.""" + task = GenerationTask.create( + project_id="p1", + asset_library_id="lib1", + asset_ids=None, + title_ids=None, + voice_ids=None, + ) + assert task.asset_ids == [] + assert task.title_ids == [] + assert task.voice_ids == [] + + def test_create_unique_id(self): + """不同任务 id 不同.""" + t1 = GenerationTask.create("p", "l") + t2 = GenerationTask.create("p", "l") + assert t1.id != t2.id + + def test_create_has_created_at(self): + """有创建时间.""" + task = GenerationTask.create("p", "l") + assert task.created_at is not None + + def test_create_defaults_started_completed_none(self): + """started_at 和 completed_at 默认 None.""" + task = GenerationTask.create("p", "l") + assert task.started_at is None + assert task.completed_at is None + + def test_empty_lists_independent(self): + """不同任务的空列表互不影响.""" + t1 = GenerationTask.create("p", "l") + t2 = GenerationTask.create("p", "l") + t1.asset_ids.append("x") + assert t2.asset_ids == [] -- 2.54.0 From 85efa7ffbbc03b42e5fc74743b357f81387845bd Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:45:54 +0800 Subject: [PATCH 7/9] =?UTF-8?q?test(wave157):=20domain=E5=B1=827=E4=B8=AA?= =?UTF-8?q?=E5=B0=8F=E6=A8=A1=E5=9D=97=E6=89=B9=E9=87=8F=E5=8D=95=E6=B5=8B?= =?UTF-8?q?=20+44?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain 层 7 个小模块新增 44 个单测,纯逻辑 0 外部依赖: - EditingMode 枚举:6个 - Tag 工厂:4个 - RecipeItem/Recipe:6个 - VoiceLibraryItem:3个 - TitleLibraryItem:3个 - TemplateSegment/Template/TemplateCategory:6个 - EditTemplateStatus/EditTemplate:16个 --- .../unit/domain/test_domain_small_modules.py | 421 ++++++++++++++++++ 1 file changed, 421 insertions(+) create mode 100644 tests/unit/domain/test_domain_small_modules.py diff --git a/tests/unit/domain/test_domain_small_modules.py b/tests/unit/domain/test_domain_small_modules.py new file mode 100644 index 000000000..55404f2f9 --- /dev/null +++ b/tests/unit/domain/test_domain_small_modules.py @@ -0,0 +1,421 @@ +"""domain层小模块批量单测. + +覆盖:recipe / tag / editing_mode / voice_library / title_library / template / edit_template +共 7 个模块,纯逻辑 0 外部依赖。 +""" + +from __future__ import annotations + +from packages.domain.editing_mode import EditingMode +from packages.domain.edit_template import EditTemplate, EditTemplateStatus +from packages.domain.recipe import Recipe, RecipeItem +from packages.domain.tag import Tag +from packages.domain.template import Template, TemplateCategory, TemplateSegment +from packages.domain.title_library import TitleLibraryItem +from packages.domain.voice_library import VoiceLibraryItem + + +class TestEditingMode: + """EditingMode 枚举测试.""" + + def test_four_modes(self): + """四种剪辑模式.""" + assert len(EditingMode) == 4 + + def test_one_take(self): + assert EditingMode.ONE_TAKE == "one_take" + + def test_pip(self): + assert EditingMode.PIP == "pip" + + def test_voice_over(self): + assert EditingMode.VOICE_OVER == "voice_over" + + def test_voice_pip(self): + assert EditingMode.VOICE_PIP == "voice_pip" + + def test_all_values_unique(self): + values = [m.value for m in EditingMode] + assert len(values) == len(set(values)) + + +class TestTag: + """Tag 测试.""" + + def test_create_valid(self): + """正常创建.""" + tag = Tag.create(user_id="u1", name=" 搞笑 ") + assert tag.user_id == "u1" + assert tag.name == "搞笑" + assert isinstance(tag.id, str) + assert len(tag.id) > 0 + assert tag.created_at is not None + + def test_create_empty_name(self): + """空名称无效.""" + try: + Tag.create("u1", "") + assert False + except ValueError as e: + assert "不能为空" in str(e) + + def test_create_whitespace_name(self): + """纯空白名称无效.""" + try: + Tag.create("u1", " ") + assert False + except ValueError as e: + assert "不能为空" in str(e) + + def test_create_unique_id(self): + t1 = Tag.create("u", "t1") + t2 = Tag.create("u", "t2") + assert t1.id != t2.id + + +class TestRecipeItem: + """RecipeItem 测试.""" + + def test_create_asset_item(self): + """素材配方项.""" + item = RecipeItem( + id="item1", + recipe_id="r1", + item_type="asset", + item_id="a1", + position=0, + ) + assert item.item_type == "asset" + assert item.item_id == "a1" + assert item.position == 0 + + def test_create_title_item(self): + """标题配方项.""" + item = RecipeItem(id="i2", recipe_id="r1", item_type="title", item_id="t1", position=1) + assert item.item_type == "title" + assert item.position == 1 + + def test_default_metadata(self): + """默认 metadata 为空 dict.""" + item = RecipeItem(id="i1", recipe_id="r1", item_type="voice", item_id="v1") + assert item.metadata_ == {} + + +class TestRecipe: + """Recipe 测试.""" + + def test_create_minimal(self): + """最简配方.""" + recipe = Recipe(id="r1", user_id="u1", name="我的配方") + assert recipe.name == "我的配方" + assert recipe.description == "" + assert recipe.template_id == "" + assert recipe.generation_params == {} + assert recipe.items == [] + assert recipe.is_active is True + assert recipe.created_at is not None + assert recipe.updated_at is not None + + def test_create_with_items(self): + """带配方项.""" + items = [ + RecipeItem(id="i1", recipe_id="r1", item_type="asset", item_id="a1", position=0), + RecipeItem(id="i2", recipe_id="r1", item_type="title", item_id="t1", position=1), + ] + recipe = Recipe(id="r1", user_id="u1", name="配方", items=items) + assert len(recipe.items) == 2 + assert recipe.items[0].item_type == "asset" + assert recipe.items[1].position == 1 + + def test_default_items_empty_list(self): + """默认 items 为空列表.""" + r1 = Recipe(id="r1", user_id="u1", name="r1") + r2 = Recipe(id="r2", user_id="u2", name="r2") + r1.items.append("fake") + assert r2.items == [] + + +class TestVoiceLibraryItem: + """VoiceLibraryItem 测试.""" + + def test_create_minimal(self): + """最简创建.""" + item = VoiceLibraryItem(id="v1", user_id="u1", name="我的配音") + assert item.name == "我的配音" + assert item.text == "" + assert item.voice_provider == "" + assert item.voice_id == "" + assert item.voice_name == "" + assert item.audio_url == "" + assert item.duration == 0 + assert item.file_size == 0 + assert item.status == "completed" + assert item.project_id is None + assert item.tags == [] + assert item.metadata_ == {} + + def test_create_full(self): + """带全部字段.""" + item = VoiceLibraryItem( + id="v1", + user_id="u1", + name="旁白", + text="大家好", + voice_provider="xf", + voice_id="v1", + voice_name="小云", + audio_url="http://x/a.mp3", + duration=10.5, + file_size=102400, + status="processing", + project_id="p1", + tags=["旁白", "正式"], + ) + assert item.text == "大家好" + assert item.duration == 10.5 + assert item.file_size == 102400 + assert item.project_id == "p1" + assert item.tags == ["旁白", "正式"] + + def test_tags_independent(self): + """不同实例的 tags 独立.""" + i1 = VoiceLibraryItem(id="v1", user_id="u", name="n1") + i2 = VoiceLibraryItem(id="v2", user_id="u", name="n2") + i1.tags.append("x") + assert i2.tags == [] + + +class TestTitleLibraryItem: + """TitleLibraryItem 测试.""" + + def test_create_required(self): + """必填字段.""" + item = TitleLibraryItem(id="t1", user_id="u1", name="爆款标题", text="这也太牛了") + assert item.name == "爆款标题" + assert item.text == "这也太牛了" + assert item.category == "default" + assert item.description == "" + assert item.tags == [] + assert item.usage_count == 0 + assert item.is_active is True + assert item.metadata_ == {} + + def test_create_full(self): + """带全部字段.""" + item = TitleLibraryItem( + id="t1", + user_id="u1", + name="科技标题", + text="震惊!", + category="tech", + description="科技类标题", + tags=["科技", "爆款"], + usage_count=100, + is_active=False, + ) + assert item.category == "tech" + assert item.usage_count == 100 + assert item.is_active is False + assert item.tags == ["科技", "爆款"] + + def test_tags_independent(self): + i1 = TitleLibraryItem(id="t1", user_id="u", name="n", text="t") + i2 = TitleLibraryItem(id="t2", user_id="u", name="n", text="t") + i1.tags.append("x") + assert i2.tags == [] + + +class TestTemplateSegment: + """TemplateSegment 测试.""" + + def test_create(self): + """正常创建.""" + seg = TemplateSegment( + id="s1", + template_id="t1", + segment_order=0, + duration_min=2.0, + duration_max=5.0, + ) + assert seg.segment_order == 0 + assert seg.duration_min == 2.0 + assert seg.duration_max == 5.0 + assert seg.material_type is None + + def test_with_material_type(self): + """带素材类型(voice_over模式).""" + seg = TemplateSegment( + id="s1", + template_id="t1", + segment_order=0, + duration_min=3.0, + duration_max=8.0, + material_type="person", + ) + assert seg.material_type == "person" + + def test_has_timestamps(self): + seg = TemplateSegment(id="s1", template_id="t1", segment_order=0, duration_min=1, duration_max=2) + assert seg.created_at is not None + assert seg.updated_at is not None + + +class TestTemplate: + """Template 测试.""" + + def test_create_minimal(self): + """最简模板.""" + tpl = Template(id="t1", user_id="u1", name="通用模板", mode="one_take") + assert tpl.name == "通用模板" + assert tpl.mode == "one_take" + assert tpl.category == "" + assert tpl.tags == [] + assert tpl.title_config == {} + assert tpl.subtitle_config == {} + assert tpl.bgm_config == {} + assert tpl.estimated_duration == 0.0 + assert tpl.segments == [] + assert tpl.is_active is True + + def test_create_with_segments(self): + """带片段.""" + segs = [ + TemplateSegment(id="s1", template_id="t1", segment_order=0, duration_min=2, duration_max=5), + TemplateSegment(id="s2", template_id="t1", segment_order=1, duration_min=3, duration_max=7), + ] + tpl = Template(id="t1", user_id="u1", name="模板", mode="pip", segments=segs) + assert len(tpl.segments) == 2 + assert tpl.segments[0].segment_order == 0 + + def test_segments_independent(self): + t1 = Template(id="t1", user_id="u", name="n1", mode="one_take") + t2 = Template(id="t2", user_id="u", name="n2", mode="pip") + t1.segments.append("fake") + assert t2.segments == [] + + +class TestTemplateCategory: + """TemplateCategory 测试.""" + + def test_create(self): + cat = TemplateCategory(id="c1", user_id="u1", name="科技") + assert cat.name == "科技" + assert cat.created_at is not None + + +class TestEditTemplateStatus: + """EditTemplateStatus 枚举测试.""" + + def test_two_statuses(self): + assert len(EditTemplateStatus) == 2 + + def test_active(self): + assert EditTemplateStatus.ACTIVE == "active" + + def test_inactive(self): + assert EditTemplateStatus.INACTIVE == "inactive" + + +class TestEditTemplate: + """EditTemplate 测试.""" + + def test_create_minimal(self): + """最简创建.""" + tpl = EditTemplate.create(name=" 通用模板 ") + assert tpl.name == "通用模板" + assert tpl.description == "" + assert tpl.template_type == "default" + assert tpl.config == {} + assert tpl.preview_url == "" + assert tpl.sort_weight == 0 + assert tpl.status == EditTemplateStatus.ACTIVE + assert isinstance(tpl.id, str) + assert len(tpl.id) > 0 + + def test_create_full(self): + """带全部字段.""" + tpl = EditTemplate.create( + name="口播模板", + description="口播类模板", + template_type="voice_over", + config={"style": "formal"}, + preview_url="https://x/preview.mp4", + sort_weight=100, + status=EditTemplateStatus.INACTIVE, + ) + assert tpl.name == "口播模板" + assert tpl.description == "口播类模板" + assert tpl.template_type == "voice_over" + assert tpl.config == {"style": "formal"} + assert tpl.preview_url == "https://x/preview.mp4" + assert tpl.sort_weight == 100 + assert tpl.status == EditTemplateStatus.INACTIVE + + def test_create_empty_name(self): + """空名称无效.""" + try: + EditTemplate.create(name="") + assert False + except ValueError as e: + assert "不能为空" in str(e) + + def test_create_whitespace_name(self): + """空白名称无效.""" + try: + EditTemplate.create(name=" ") + assert False + except ValueError as e: + assert "不能为空" in str(e) + + def test_empty_template_type_defaults(self): + """空 template_type 默认 default.""" + tpl = EditTemplate.create(name="t", template_type="") + assert tpl.template_type == "default" + + def test_whitespace_template_type_defaults(self): + """空白 template_type 默认 default.""" + tpl = EditTemplate.create(name="t", template_type=" ") + assert tpl.template_type == "default" + + def test_config_none_defaults_empty(self): + """config=None 默认为空 dict.""" + tpl = EditTemplate.create(name="t", config=None) + assert tpl.config == {} + + def test_activate(self): + """激活.""" + tpl = EditTemplate.create(name="t", status=EditTemplateStatus.INACTIVE) + old = tpl.updated_at + tpl.activate() + assert tpl.is_active is True + assert tpl.status == EditTemplateStatus.ACTIVE + assert tpl.updated_at >= old + + def test_deactivate(self): + """停用.""" + tpl = EditTemplate.create(name="t") + old = tpl.updated_at + tpl.deactivate() + assert tpl.is_active is False + assert tpl.status == EditTemplateStatus.INACTIVE + assert tpl.updated_at >= old + + def test_is_active_property(self): + """is_active 属性.""" + tpl = EditTemplate.create(name="t") + assert tpl.is_active is True + tpl.deactivate() + assert tpl.is_active is False + tpl.activate() + assert tpl.is_active is True + + def test_unique_id(self): + t1 = EditTemplate.create(name="t1") + t2 = EditTemplate.create(name="t2") + assert t1.id != t2.id + + def test_config_independent(self): + t1 = EditTemplate.create(name="t1") + t2 = EditTemplate.create(name="t2") + t1.config["k"] = "v" + assert "k" not in t2.config -- 2.54.0 From c993279ea2c1dd13b34885e93c85e4b9733922f1 Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:48:03 +0800 Subject: [PATCH 8/9] =?UTF-8?q?test(wave158):=20edit=5Fplan=E5=89=AA?= =?UTF-8?q?=E8=BE=91=E8=AE=A1=E5=88=92=E5=8D=95=E6=B5=8B=20+32?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/edit_plan.py 新增 32 个单测: - EditPlanStatus 枚举:6个 - create 工厂/校验:11个(必填/strip/空值/默认值) - 状态流转(draft→editing→rendering→completed/failed):14个 - config 独立性:1个 --- tests/unit/domain/test_edit_plan.py | 296 ++++++++++++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 tests/unit/domain/test_edit_plan.py diff --git a/tests/unit/domain/test_edit_plan.py b/tests/unit/domain/test_edit_plan.py new file mode 100644 index 000000000..8a19bd6a6 --- /dev/null +++ b/tests/unit/domain/test_edit_plan.py @@ -0,0 +1,296 @@ +"""edit_plan 单测. + +domain 层剪辑计划纯逻辑模块,0 外部依赖。 +覆盖:枚举常量、create工厂/校验、完整状态流转、重置。 +""" + +from __future__ import annotations + +from packages.domain.edit_plan import EditPlan, EditPlanStatus + + +class TestEditPlanStatus: + """EditPlanStatus 枚举测试.""" + + def test_five_statuses(self): + """五种状态.""" + assert len(EditPlanStatus) == 5 + + def test_draft(self): + assert EditPlanStatus.DRAFT == "draft" + + def test_editing(self): + assert EditPlanStatus.EDITING == "editing" + + def test_rendering(self): + assert EditPlanStatus.RENDERING == "rendering" + + def test_completed(self): + assert EditPlanStatus.COMPLETED == "completed" + + def test_failed(self): + assert EditPlanStatus.FAILED == "failed" + + +class TestEditPlanCreate: + """EditPlan.create 工厂测试.""" + + def test_create_minimal(self): + """最简创建.""" + plan = EditPlan.create(template_id="tpl1", name=" 我的计划 ") + assert plan.template_id == "tpl1" + assert plan.name == "我的计划" + assert plan.status == EditPlanStatus.DRAFT + assert plan.total_duration == 0.0 + assert plan.config == {} + assert plan.project_id == "" + assert plan.created_by_user_id == "" + assert isinstance(plan.id, str) + assert len(plan.id) > 0 + + def test_create_full(self): + """带全部字段.""" + plan = EditPlan.create( + template_id="tpl1", + name="口播视频计划", + config={"bgm": "rock"}, + total_duration=120.5, + source_edit_plan_id="src1", + project_id="proj1", + created_by_user_id="user1", + ) + assert plan.name == "口播视频计划" + assert plan.total_duration == 120.5 + assert plan.source_edit_plan_id == "src1" + assert plan.project_id == "proj1" + assert plan.created_by_user_id == "user1" + assert plan.config == {"bgm": "rock"} + + def test_create_empty_name(self): + """空名称无效.""" + try: + EditPlan.create(template_id="t1", name="") + assert False + except ValueError as e: + assert "名称" in str(e) + + def test_create_whitespace_name(self): + """空白名称无效.""" + try: + EditPlan.create(template_id="t1", name=" ") + assert False + except ValueError as e: + assert "名称" in str(e) + + def test_create_empty_template_id(self): + """空 template_id 无效.""" + try: + EditPlan.create(template_id="", name="计划") + assert False + except ValueError as e: + assert "template_id" in str(e) + + def test_create_whitespace_template_id(self): + """空白 template_id 无效.""" + try: + EditPlan.create(template_id=" ", name="计划") + assert False + except ValueError as e: + assert "template_id" in str(e) + + def test_config_none_defaults_empty(self): + """config=None 默认为空 dict.""" + plan = EditPlan.create(template_id="t1", name="p", config=None) + assert plan.config == {} + + def test_unique_id(self): + """不同计划 id 不同.""" + p1 = EditPlan.create("t", "p1") + p2 = EditPlan.create("t", "p2") + assert p1.id != p2.id + + def test_has_timestamps(self): + """有创建和更新时间.""" + plan = EditPlan.create("t", "p") + assert plan.created_at is not None + assert plan.updated_at is not None + + def test_strips_string_fields(self): + """字符串字段 strip.""" + plan = EditPlan.create( + template_id=" t1 ", + name=" n ", + source_edit_plan_id=" s ", + project_id=" p ", + created_by_user_id=" u ", + ) + assert plan.template_id == "t1" + assert plan.name == "n" + assert plan.source_edit_plan_id == "s" + assert plan.project_id == "p" + assert plan.created_by_user_id == "u" + + +class TestEditPlanStatusFlow: + """状态流转测试.""" + + def _make_plan(self): + return EditPlan.create(template_id="t1", name="测试计划") + + def test_initial_status_draft(self): + """初始状态 draft.""" + plan = self._make_plan() + assert plan.status == EditPlanStatus.DRAFT + + def test_draft_to_editing(self): + """draft -> editing.""" + plan = self._make_plan() + old = plan.updated_at + plan.start_editing() + assert plan.status == EditPlanStatus.EDITING + assert plan.updated_at >= old + + def test_editing_to_rendering(self): + """editing -> rendering.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + assert plan.status == EditPlanStatus.RENDERING + + def test_rendering_to_completed(self): + """rendering -> completed.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_completed() + assert plan.status == EditPlanStatus.COMPLETED + + def test_rendering_to_failed(self): + """rendering -> failed.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_failed() + assert plan.status == EditPlanStatus.FAILED + + def test_failed_to_draft_reset(self): + """failed -> draft 重置.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_failed() + plan.reset_to_draft() + assert plan.status == EditPlanStatus.DRAFT + + def test_cannot_editing_from_completed(self): + """completed 不能 start_editing.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_completed() + try: + plan.start_editing() + assert False + except ValueError as e: + assert "draft" in str(e).lower() + + def test_cannot_rendering_from_draft(self): + """draft 不能直接 start_rendering.""" + plan = self._make_plan() + try: + plan.start_rendering() + assert False + except ValueError as e: + assert "editing" in str(e).lower() + + def test_cannot_complete_from_editing(self): + """editing 不能直接完成.""" + plan = self._make_plan() + plan.start_editing() + try: + plan.mark_completed() + assert False + except ValueError as e: + assert "rendering" in str(e).lower() + + def test_cannot_fail_from_editing(self): + """editing 不能直接失败.""" + plan = self._make_plan() + plan.start_editing() + try: + plan.mark_failed() + assert False + except ValueError as e: + assert "rendering" in str(e).lower() + + def test_cannot_reset_from_draft(self): + """draft 不能重置.""" + plan = self._make_plan() + try: + plan.reset_to_draft() + assert False + except ValueError as e: + assert "failed" in str(e).lower() + + def test_cannot_reset_from_completed(self): + """completed 不能重置.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_completed() + try: + plan.reset_to_draft() + assert False + except ValueError as e: + assert "failed" in str(e).lower() + + def test_full_happy_path(self): + """完整成功路径.""" + plan = self._make_plan() + assert plan.status == EditPlanStatus.DRAFT + plan.start_editing() + assert plan.status == EditPlanStatus.EDITING + plan.start_rendering() + assert plan.status == EditPlanStatus.RENDERING + plan.mark_completed() + assert plan.status == EditPlanStatus.COMPLETED + + def test_failed_reset_retry(self): + """失败后重置重试完整路径.""" + plan = self._make_plan() + plan.start_editing() + plan.start_rendering() + plan.mark_failed() + assert plan.status == EditPlanStatus.FAILED + plan.reset_to_draft() + assert plan.status == EditPlanStatus.DRAFT + # 重新走一遍 + plan.start_editing() + plan.start_rendering() + plan.mark_completed() + assert plan.status == EditPlanStatus.COMPLETED + + def test_each_transition_updates_timestamp(self): + """每次状态变更都更新 updated_at.""" + plan = self._make_plan() + timestamps = [plan.updated_at] + plan.start_editing() + timestamps.append(plan.updated_at) + plan.start_rendering() + timestamps.append(plan.updated_at) + plan.mark_completed() + timestamps.append(plan.updated_at) + # 单调递增 + for i in range(1, len(timestamps)): + assert timestamps[i] >= timestamps[i - 1] + + +class TestEditPlanConfig: + """config 独立性测试.""" + + def test_config_independent(self): + """不同计划的 config 独立.""" + p1 = EditPlan.create(template_id="t", name="p1") + p2 = EditPlan.create(template_id="t", name="p2") + p1.config["key"] = "value" + assert "key" not in p2.config -- 2.54.0 From a73f8176cd8ea5a711fd20e6371ae8610142425f Mon Sep 17 00:00:00 2001 From: xiaoxia Date: Tue, 28 Jul 2026 13:50:12 +0800 Subject: [PATCH 9/9] =?UTF-8?q?test(wave159):=20template=5Fclip=5Fconfig?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=89=87=E6=AE=B5=E9=85=8D=E7=BD=AE=E5=8D=95?= =?UTF-8?q?=E6=B5=8B=20+41?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为 domain/template_clip_config.py 新增 41 个单测: - ClipType 枚举:8个 - TransitionEffect 枚举:7个 - create 工厂/校验:17个(必填/边界/字符串枚举转换/默认值) - has_duration_range / default_duration 属性:9个 --- .../unit/domain/test_template_clip_config.py | 347 ++++++++++++++++++ 1 file changed, 347 insertions(+) create mode 100644 tests/unit/domain/test_template_clip_config.py diff --git a/tests/unit/domain/test_template_clip_config.py b/tests/unit/domain/test_template_clip_config.py new file mode 100644 index 000000000..fdc1fc647 --- /dev/null +++ b/tests/unit/domain/test_template_clip_config.py @@ -0,0 +1,347 @@ +"""template_clip_config 单测. + +domain 层模板片段配置纯逻辑模块,0 外部依赖。 +覆盖:ClipType枚举、TransitionEffect枚举、create工厂/校验、计算属性。 +""" + +from __future__ import annotations + +from packages.domain.template_clip_config import ( + ClipType, + TemplateClipConfig, + TransitionEffect, +) + + +class TestClipType: + """ClipType 枚举测试.""" + + def test_six_types(self): + """六种片段类型.""" + assert len(ClipType) == 6 + + def test_intro(self): + assert ClipType.INTRO == "intro" + + def test_main(self): + assert ClipType.MAIN == "main" + + def test_transition(self): + assert ClipType.TRANSITION == "transition" + + def test_outro(self): + assert ClipType.OUTRO == "outro" + + def test_title(self): + assert ClipType.TITLE == "title" + + def test_subtitle(self): + assert ClipType.SUBTITLE == "subtitle" + + def test_from_string(self): + """可从字符串构造.""" + assert ClipType("main") == ClipType.MAIN + assert ClipType("intro") == ClipType.INTRO + + +class TestTransitionEffect: + """TransitionEffect 枚举测试.""" + + def test_six_effects(self): + """六种转场效果.""" + assert len(TransitionEffect) == 6 + + def test_cut(self): + assert TransitionEffect.CUT == "cut" + + def test_fade(self): + assert TransitionEffect.FADE == "fade" + + def test_slide_left(self): + assert TransitionEffect.SLIDE_LEFT == "slide_left" + + def test_slide_right(self): + assert TransitionEffect.SLIDE_RIGHT == "slide_right" + + def test_dissolve(self): + assert TransitionEffect.DISSOLVE == "dissolve" + + def test_wipe(self): + assert TransitionEffect.WIPE == "wipe" + + def test_from_string(self): + """可从字符串构造.""" + assert TransitionEffect("fade") == TransitionEffect.FADE + assert TransitionEffect("cut") == TransitionEffect.CUT + + +class TestTemplateClipConfigCreate: + """TemplateClipConfig.create 工厂测试.""" + + def test_create_minimal(self): + """最简创建.""" + clip = TemplateClipConfig.create( + template_id="tpl1", + clip_type=ClipType.MAIN, + order=0, + ) + assert clip.template_id == "tpl1" + assert clip.clip_type == ClipType.MAIN + assert clip.order == 0 + assert clip.min_duration == 0.0 + assert clip.max_duration == 0.0 + assert clip.text_template == "" + assert clip.material_requirements == {} + assert clip.transition_effect == TransitionEffect.CUT + assert clip.config == {} + assert isinstance(clip.id, str) + assert len(clip.id) > 0 + + def test_create_with_string_clip_type(self): + """用字符串传 clip_type.""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type="intro", + order=0, + ) + assert clip.clip_type == ClipType.INTRO + + def test_create_with_string_transition(self): + """用字符串传 transition_effect.""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + transition_effect="fade", + ) + assert clip.transition_effect == TransitionEffect.FADE + + def test_create_full(self): + """带全部字段.""" + clip = TemplateClipConfig.create( + template_id=" tpl1 ", + clip_type=ClipType.TITLE, + order=2, + min_duration=2.0, + max_duration=5.0, + text_template=" 欢迎关注 ", + material_requirements={"category": "scenic"}, + transition_effect=TransitionEffect.FADE, + config={"font_size": 24}, + ) + assert clip.template_id == "tpl1" # strip + assert clip.clip_type == ClipType.TITLE + assert clip.order == 2 + assert clip.min_duration == 2.0 + assert clip.max_duration == 5.0 + assert clip.text_template == "欢迎关注" # strip + assert clip.material_requirements == {"category": "scenic"} + assert clip.transition_effect == TransitionEffect.FADE + assert clip.config == {"font_size": 24} + + def test_create_empty_template_id(self): + """空 template_id 无效.""" + try: + TemplateClipConfig.create(template_id="", clip_type=ClipType.MAIN, order=0) + assert False + except ValueError as e: + assert "template_id" in str(e) + + def test_create_whitespace_template_id(self): + """空白 template_id 无效.""" + try: + TemplateClipConfig.create(template_id=" ", clip_type=ClipType.MAIN, order=0) + assert False + except ValueError as e: + assert "template_id" in str(e) + + def test_create_negative_min_duration(self): + """min_duration 为负无效.""" + try: + TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + min_duration=-1.0, + ) + assert False + except ValueError as e: + assert "min_duration" in str(e) + + def test_create_negative_max_duration(self): + """max_duration 为负无效.""" + try: + TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + max_duration=-1.0, + ) + assert False + except ValueError as e: + assert "max_duration" in str(e) + + def test_create_min_greater_than_max(self): + """min > max 且 max > 0 时无效.""" + try: + TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + min_duration=5.0, + max_duration=3.0, + ) + assert False + except ValueError as e: + assert "min_duration" in str(e) and "max_duration" in str(e) + + def test_create_min_equals_max_valid(self): + """min == max 合法.""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + min_duration=3.0, + max_duration=3.0, + ) + assert clip.min_duration == 3.0 + assert clip.max_duration == 3.0 + + def test_create_zero_both_valid(self): + """都为 0 合法(未设置时长).""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + min_duration=0.0, + max_duration=0.0, + ) + assert clip.min_duration == 0.0 + assert clip.max_duration == 0.0 + + def test_create_invalid_clip_type_string(self): + """无效的 clip_type 字符串抛错.""" + try: + TemplateClipConfig.create(template_id="t1", clip_type="invalid", order=0) + assert False + except ValueError: + pass # 枚举构造失败会抛 ValueError + + def test_create_material_req_none_defaults_empty(self): + """material_requirements=None 默认为空 dict.""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + material_requirements=None, + ) + assert clip.material_requirements == {} + + def test_create_config_none_defaults_empty(self): + """config=None 默认为空 dict.""" + clip = TemplateClipConfig.create( + template_id="t1", + clip_type=ClipType.MAIN, + order=0, + config=None, + ) + assert clip.config == {} + + def test_create_unique_id(self): + """不同配置 id 不同.""" + c1 = TemplateClipConfig.create("t", ClipType.MAIN, 0) + c2 = TemplateClipConfig.create("t", ClipType.MAIN, 0) + assert c1.id != c2.id + + def test_create_has_timestamps(self): + """有创建和更新时间.""" + clip = TemplateClipConfig.create("t", ClipType.MAIN, 0) + assert clip.created_at is not None + assert clip.updated_at is not None + + +class TestTemplateClipConfigProperties: + """计算属性测试.""" + + def test_has_duration_range_false_zero(self): + """都为 0 时没有时长范围.""" + clip = TemplateClipConfig.create("t", ClipType.MAIN, 0) + assert clip.has_duration_range is False + + def test_has_duration_range_true_min_only(self): + """只有 min > 0 也算有范围.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + min_duration=2.0, + ) + assert clip.has_duration_range is True + + def test_has_duration_range_true_max_only(self): + """只有 max > 0 也算有范围.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + max_duration=5.0, + ) + assert clip.has_duration_range is True + + def test_has_duration_range_true_both(self): + """两者都 > 0 有范围.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + min_duration=2.0, + max_duration=5.0, + ) + assert clip.has_duration_range is True + + def test_default_duration_zero(self): + """都为 0 默认时长 0.""" + clip = TemplateClipConfig.create("t", ClipType.MAIN, 0) + assert clip.default_duration == 0.0 + + def test_default_duration_middle(self): + """两者都有取中间值.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + min_duration=2.0, + max_duration=6.0, + ) + assert clip.default_duration == 4.0 + + def test_default_duration_min_only(self): + """只有 min 用 min.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + min_duration=3.0, + ) + assert clip.default_duration == 3.0 + + def test_default_duration_max_only(self): + """只有 max 用 max.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + max_duration=5.0, + ) + assert clip.default_duration == 5.0 + + def test_default_duration_equal_min_max(self): + """min == max 时值相等.""" + clip = TemplateClipConfig.create( + "t", + ClipType.MAIN, + 0, + min_duration=3.0, + max_duration=3.0, + ) + assert clip.default_duration == 3.0 -- 2.54.0