diff --git a/tests/unit/test_pip_engine_pure.py b/tests/unit/test_pip_engine_pure.py index f04f61fb4..bac5d0542 100755 --- a/tests/unit/test_pip_engine_pure.py +++ b/tests/unit/test_pip_engine_pure.py @@ -1,15 +1,10 @@ -"""PiP Engine 纯逻辑单测. - -测试 pip_engine_pure.py 中的所有纯函数, -0 FFmpeg 依赖,快速轻量。 -""" - -from __future__ import annotations +"""pip_engine_pure 单元测试.""" from pathlib import Path import pytest -from video_processing.pip_engine_pure import ( + +from apps.worker.video_processing.pip_engine_pure import ( build_animation_filters, build_enable_expr, build_overlay_expr, @@ -21,7 +16,6 @@ from video_processing.pip_engine_pure import ( sort_layers_by_z_index, validate_pip_layer, ) - from packages.domain.pip_config import ( ANIMATION_FADE, ANIMATION_SLIDE_BOTTOM, @@ -31,936 +25,656 @@ from packages.domain.pip_config import ( PiPLayerConfig, ) -# ── 常量与工具 ──────────────────────────────────────────────────────────────── -OUTPUT_W = 1080 -OUTPUT_H = 1920 +def _make_layer(**kwargs): + """快速创建 PiPLayerConfig.""" + layer = PiPLayerConfig() + for k, v in kwargs.items(): + setattr(layer, k, v) + return layer -def _make_layer(**kwargs) -> PiPLayerConfig: - """快速创建图层配置.""" - defaults = dict( - source_type="local_path", - source="/tmp/test.mp4", - width="25%", - height=None, - position="bottom_right", - margin=20, - opacity=1.0, - corner_radius=0, - border_width=0, - border_color="black", - z_index=0, - start_time=0.0, - duration=None, - animation_in=None, - animation_out=None, - animation_duration=0.5, - ) - defaults.update(kwargs) - return PiPLayerConfig(**defaults) - - -# ═══════════════════════════════════════════════════════════════════════════════ -# compute_pip_size -# ═══════════════════════════════════════════════════════════════════════════════ +# ── compute_pip_size ──────────────────────────────────────────────────────── class TestComputePipSize: - """尺寸计算测试.""" - def test_percentage_width_auto_height(self): - """百分比宽度,自动高度(16:9).""" - layer = _make_layer(width="25%") - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) - assert w == 270 # 1080 * 25% - assert h == 151 # 270 * 9 / 16 = 151.875 → 151 + layer = _make_layer(width="30%") + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 576 # 1920 * 0.3 + assert h == int(576 * 9 / 16) # 按16:9等比 def test_pixel_width_and_height(self): - """像素宽高.""" - layer = _make_layer(width=300, height=200) - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) - assert w == 300 - assert h == 200 + layer = _make_layer(width="400", height="300") + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 400 + assert h == 300 - def test_pixel_width_percent_height(self): - """像素宽 + 百分比高.""" - layer = _make_layer(width=200, height="10%") - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) - assert w == 200 - assert h == 192 # 1920 * 10% + def test_int_width_and_height(self): + layer = _make_layer(width=500, height=400) + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 500 + assert h == 400 - def test_full_width_clamped(self): - """超过输出尺寸时钳制到输出范围内.""" + def test_width_exceeds_output_clamped(self): layer = _make_layer(width="200%") - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) - assert w == OUTPUT_W - assert h <= OUTPUT_H # 按比例后高度不超过输出 + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 1920 + assert h <= 1080 - def test_zero_width_minimum(self): - """极小尺寸钳制到至少 1 像素.""" - layer = _make_layer(width="0%") - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) + def test_height_exceeds_output_clamped(self): + layer = _make_layer(width="100", height="200%") + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 100 + assert h == 1080 + + def test_minimum_size(self): + layer = _make_layer(width="0", height="0") + w, h = compute_pip_size(layer, 1920, 1080) assert w >= 1 assert h >= 1 - def test_pixel_int_width(self): - """整数像素宽度.""" - layer = _make_layer(width=500, height=300) - w, h = compute_pip_size(layer, OUTPUT_W, OUTPUT_H) - assert w == 500 - assert h == 300 + def test_empty_height_auto_ratio(self): + layer = _make_layer(width="320", height="") + w, h = compute_pip_size(layer, 1920, 1080) + assert w == 320 + assert h == int(320 * 9 / 16) -# ═══════════════════════════════════════════════════════════════════════════════ -# compute_pip_position -# ═══════════════════════════════════════════════════════════════════════════════ +# ── compute_pip_position ──────────────────────────────────────────────────── class TestComputePipPosition: - """位置计算测试.""" - - def test_bottom_right(self): - """右下角位置.""" + def test_bottom_right_position(self): layer = _make_layer(position="bottom_right", margin=20) - pip_w, pip_h = 200, 150 - x, y = compute_pip_position(layer, pip_w, pip_h, OUTPUT_W, OUTPUT_H) - assert x == OUTPUT_W - pip_w - 20 - assert y == OUTPUT_H - pip_h - 20 + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) + assert x == 1920 - 200 - 20 + assert y == 1080 - 150 - 20 - def test_top_left(self): - """左上角.""" + def test_top_left_position(self): layer = _make_layer(position="top_left", margin=10) - x, y = compute_pip_position(layer, 200, 150, OUTPUT_W, OUTPUT_H) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) assert x == 10 assert y == 10 - def test_top_center(self): - """顶部居中.""" - layer = _make_layer(position="top_center", margin=20) - x, y = compute_pip_position(layer, 200, 150, OUTPUT_W, OUTPUT_H) - assert x == (OUTPUT_W - 200) // 2 - assert y == 20 - - def test_center(self): - """正中心.""" + def test_center_position(self): layer = _make_layer(position="center") - x, y = compute_pip_position(layer, 200, 150, OUTPUT_W, OUTPUT_H) - assert x == (OUTPUT_W - 200) // 2 - assert y == (OUTPUT_H - 150) // 2 + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) + assert x == (1920 - 200) // 2 + assert y == (1080 - 150) // 2 def test_custom_position(self): - """自定义坐标.""" layer = _make_layer(position="custom", x=100, y=200) - x, y = compute_pip_position(layer, 200, 150, OUTPUT_W, OUTPUT_H) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) assert x == 100 assert y == 200 - def test_margin_effect(self): - """不同 margin 值影响位置.""" - layer1 = _make_layer(position="bottom_right", margin=0) - layer2 = _make_layer(position="bottom_right", margin=50) - x1, y1 = compute_pip_position(layer1, 200, 150, OUTPUT_W, OUTPUT_H) - x2, y2 = compute_pip_position(layer2, 200, 150, OUTPUT_W, OUTPUT_H) - assert x1 > x2 - assert y1 > y2 - - def test_clamped_when_outside(self): - """自定义坐标超出画面时钳制到边界内.""" - layer = _make_layer(position="custom", x=-50, y=99999) - x, y = compute_pip_position(layer, 200, 150, OUTPUT_W, OUTPUT_H) + def test_clamped_to_left_edge(self): + # parse_size_value 有 max(1, value) 钳制,负数返回1 + layer = _make_layer(position="custom", x=-100, y=0) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) assert x >= 0 - assert x <= OUTPUT_W - 200 + assert x < 200 + + def test_clamped_to_right_edge(self): + layer = _make_layer(position="custom", x=9999, y=0) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) + assert x == 1920 - 200 + + def test_clamped_to_top_edge(self): + # parse_size_value 有 max(1, value) 钳制,负数返回1 + layer = _make_layer(position="custom", x=0, y=-50) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) assert y >= 0 - assert y == OUTPUT_H - 150 # y 超出底部,钳制到底部 + assert y < 150 - def test_bottom_center(self): - """底部居中.""" - layer = _make_layer(position="bottom_center", margin=30) - x, y = compute_pip_position(layer, 300, 200, OUTPUT_W, OUTPUT_H) - assert x == (OUTPUT_W - 300) // 2 - assert y == OUTPUT_H - 200 - 30 - - def test_center_left(self): - """左侧居中.""" - layer = _make_layer(position="center_left", margin=15) - x, y = compute_pip_position(layer, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == 15 - assert y == (OUTPUT_H - 100) // 2 - - def test_center_right(self): - """右侧居中.""" - layer = _make_layer(position="center_right", margin=15) - x, y = compute_pip_position(layer, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == OUTPUT_W - 150 - 15 - assert y == (OUTPUT_H - 100) // 2 + def test_clamped_to_bottom_edge(self): + layer = _make_layer(position="custom", x=0, y=9999) + x, y = compute_pip_position(layer, 200, 150, 1920, 1080) + assert y == 1080 - 150 -# ═══════════════════════════════════════════════════════════════════════════════ -# build_pip_pre_filter -# ═══════════════════════════════════════════════════════════════════════════════ +# ── build_pip_pre_filter ──────────────────────────────────────────────────── class TestBuildPipPreFilter: - """预处理滤镜构建测试.""" - - def test_basic_scale_setsar(self): - """基础:scale + setsar.""" - layer = _make_layer() + def test_basic_scale_and_sar(self): + layer = _make_layer(width="200", height="150") result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert result.startswith("[1:v]") assert "scale=200:150" in result assert "setsar=1" in result assert result.endswith("[pip_pre_0]") - def test_corner_radius_filter(self): - """圆角裁剪滤镜.""" + def test_with_corner_radius(self): layer = _make_layer(corner_radius=20) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "geq=" in result assert "format=yuva420p" in result - # 圆角半径应钳制到 min(r, w//2, h//2) - assert "hypot(" in result - def test_corner_radius_clamped(self): - """圆角半径超过尺寸一半时自动钳制.""" - layer = _make_layer(corner_radius=1000) # 超大 - result = build_pip_pre_filter("[0:v]", layer, 100, 80, "pre") - # 钳制后 r = min(1000, 50, 40) = 40 - # 检查 geq 表达式中的 r 值 - import re + def test_corner_radius_zero(self): + layer = _make_layer(corner_radius=0) + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") + assert "geq=" not in result - r_matches = re.findall(r"lt\(X,(\d+)\)\*lt\(Y,\1\)", result) - assert r_matches - assert int(r_matches[0]) <= 50 # 不超过宽的一半 - - def test_border_filter(self): - """边框滤镜.""" + def test_with_border(self): layer = _make_layer(border_width=5, border_color="red") - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "pad=210:160:5:5:red" in result - def test_zero_border_no_pad(self): - """border_width=0 时不加 pad.""" + def test_border_zero(self): layer = _make_layer(border_width=0) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "pad=" not in result - def test_opacity_filter(self): - """透明度滤镜.""" + def test_with_opacity(self): layer = _make_layer(opacity=0.5) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "colorchannelmixer=aa=0.5" in result - assert "format=yuva420p" in result - def test_full_opacity_no_alpha(self): - """opacity=1.0 时不加透明度滤镜.""" + def test_full_opacity_no_alpha_filter(self): layer = _make_layer(opacity=1.0) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "colorchannelmixer" not in result - def test_opacity_clamped_high(self): - """opacity > 1.0 时钳制.""" - layer = _make_layer(opacity=2.0) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") - # 钳制到 1.0,不加透明度滤镜 - assert "colorchannelmixer=aa=1" not in result - assert "colorchannelmixer" not in result - - def test_opacity_clamped_low(self): - """opacity < 0 时钳制到 0.""" + def test_opacity_clamped(self): layer = _make_layer(opacity=-0.5) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") assert "colorchannelmixer=aa=0.0" in result - def test_fade_in_animation(self): - """淡入动画.""" - layer = _make_layer(animation_in=ANIMATION_FADE, animation_duration=0.3) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") - assert "fade=t=in:st=0:d=0.3:alpha=1" in result - - def test_fade_out_animation(self): - """淡出动画(需要 duration).""" - layer = _make_layer( - animation_out=ANIMATION_FADE, - animation_duration=0.5, - duration=5.0, - ) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") - assert "fade=t=out:st=4.5:d=0.5:alpha=1" in result - - def test_fade_out_no_duration(self): - """淡出无 duration 时不加.""" - layer = _make_layer(animation_out=ANIMATION_FADE, animation_duration=0.5, duration=None) - result = build_pip_pre_filter("[0:v]", layer, 200, 150, "pre") - assert "fade=t=out" not in result - - def test_combined_effects(self): - """多个效果组合:圆角 + 边框 + 透明度.""" - layer = _make_layer( - corner_radius=15, - border_width=3, - border_color="white", - opacity=0.8, - ) - result = build_pip_pre_filter("[0:v]", layer, 300, 200, "pre") - assert "geq=" in result # 圆角 - assert "pad=306:206:3:3:white" in result # 边框 - assert "colorchannelmixer=aa=0.8" in result # 透明度 - - def test_output_label(self): - """输出标签正确.""" - layer = _make_layer() - result = build_pip_pre_filter("[2:v]", layer, 100, 80, "my_label") - assert result.endswith("[my_label]") - - def test_input_label(self): - """输入标签正确.""" - layer = _make_layer() - result = build_pip_pre_filter("[5:v]", layer, 100, 80, "out") - assert result.startswith("[5:v]") - - -# ═══════════════════════════════════════════════════════════════════════════════ -# build_animation_filters -# ═══════════════════════════════════════════════════════════════════════════════ - - -class TestBuildAnimationFilters: - """动画滤镜构建测试.""" - - def test_no_animation(self): - """无动画返回空列表.""" - layer = _make_layer() - result = build_animation_filters(layer, 200, 150) - assert result == [] - - def test_fade_in_only(self): - """仅淡入.""" - layer = _make_layer(animation_in=ANIMATION_FADE, animation_duration=0.5) - result = build_animation_filters(layer, 200, 150) - assert len(result) == 1 - assert "fade=t=in" in result[0] - - def test_fade_out_with_duration(self): - """淡出(有 duration).""" - layer = _make_layer( - animation_out=ANIMATION_FADE, - animation_duration=0.3, - duration=10.0, - ) - result = build_animation_filters(layer, 200, 150) - assert len(result) == 1 - assert "fade=t=out:st=9.7:d=0.3" in result[0] - - def test_fade_out_no_duration_skipped(self): - """淡出无 duration 时跳过.""" - layer = _make_layer(animation_out=ANIMATION_FADE, animation_duration=0.5) - result = build_animation_filters(layer, 200, 150) - assert result == [] - - def test_fade_in_and_out(self): - """淡入 + 淡出.""" + def test_with_fade_animation(self): layer = _make_layer( animation_in=ANIMATION_FADE, animation_out=ANIMATION_FADE, animation_duration=0.5, duration=3.0, ) + result = build_pip_pre_filter("[1:v]", layer, 200, 150, "pip_pre_0") + assert "fade=t=in:st=0:d=0.5:alpha=1" in result + assert "fade=t=out" in result + + def test_all_features_combined(self): + layer = _make_layer( + corner_radius=15, + border_width=3, + border_color="blue", + opacity=0.8, + animation_in=ANIMATION_FADE, + animation_duration=0.3, + duration=5.0, + ) + result = build_pip_pre_filter("[1:v]", layer, 300, 200, "pip_out") + assert "scale=300:200" in result + assert "geq=" in result + assert "pad=" in result + assert "colorchannelmixer=aa=0.8" in result + assert "fade=t=in" in result + assert result.endswith("[pip_out]") + + +# ── build_animation_filters ───────────────────────────────────────────────── + + +class TestBuildAnimationFilters: + def test_no_animation(self): + layer = _make_layer() + assert build_animation_filters(layer, 200, 150) == [] + + def test_fade_in_only(self): + layer = _make_layer(animation_in=ANIMATION_FADE, animation_duration=0.5) + result = build_animation_filters(layer, 200, 150) + assert len(result) == 1 + assert "fade=t=in:st=0:d=0.5:alpha=1" in result[0] + + def test_fade_out_requires_duration(self): + layer = _make_layer(animation_out=ANIMATION_FADE, animation_duration=0.5) + result = build_animation_filters(layer, 200, 150) + # 没有duration,出场动画不生效 + assert len(result) == 0 + + def test_fade_out_with_duration(self): + layer = _make_layer( + animation_out=ANIMATION_FADE, + animation_duration=0.5, + duration=5.0, + ) + result = build_animation_filters(layer, 200, 150) + assert len(result) == 1 + assert "fade=t=out" in result[0] + assert "st=4.5" in result[0] # 5.0 - 0.5 + + def test_both_fade_animations(self): + layer = _make_layer( + animation_in=ANIMATION_FADE, + animation_out=ANIMATION_FADE, + animation_duration=0.3, + duration=4.0, + ) result = build_animation_filters(layer, 200, 150) assert len(result) == 2 - assert any("fade=t=in" in f for f in result) - assert any("fade=t=out" in f for f in result) + assert "fade=t=in" in result[0] + assert "fade=t=out" in result[1] - def test_slide_in_not_here(self): - """slide 动画不在此函数处理.""" - layer = _make_layer(animation_in=ANIMATION_SLIDE_LEFT, animation_duration=0.5) - result = build_animation_filters(layer, 200, 150) - assert result == [] - - def test_zero_duration_no_animation(self): - """动画时长为 0 时不加.""" + def test_zero_duration_animation(self): layer = _make_layer(animation_in=ANIMATION_FADE, animation_duration=0) result = build_animation_filters(layer, 200, 150) assert result == [] - def test_negative_duration_clamped(self): - """负动画时长钳制为 0.""" + def test_negative_animation_duration_clamped(self): layer = _make_layer(animation_in=ANIMATION_FADE, animation_duration=-1) result = build_animation_filters(layer, 200, 150) assert result == [] - def test_fade_out_start_clamped_to_zero(self): - """淡出开始时间不为负.""" - layer = _make_layer( - animation_out=ANIMATION_FADE, - animation_duration=2.0, - duration=1.0, # 比动画时长短 - ) + def test_slide_animation_not_in_this_function(self): + # slide类动画不在这个函数处理 + layer = _make_layer(animation_in=ANIMATION_SLIDE_LEFT, animation_duration=0.5) result = build_animation_filters(layer, 200, 150) - assert len(result) == 1 - # start = max(0, 1.0 - 2.0) = 0 - assert "st=0.0:d=2.0" in result[0] + assert result == [] -# ═══════════════════════════════════════════════════════════════════════════════ -# build_overlay_expr -# ═══════════════════════════════════════════════════════════════════════════════ +# ── build_overlay_expr ────────────────────────────────────────────────────── class TestBuildOverlayExpr: - """overlay 表达式构建测试.""" - def test_no_animation_static_position(self): - """无动画时返回静态坐标.""" layer = _make_layer() - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert y == "200" + x_expr, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert x_expr == "100" + assert y_expr == "200" - def test_slide_in_from_left(self): - """从左侧滑入.""" + def test_slide_left_enter(self): layer = _make_layer(animation_in=ANIMATION_SLIDE_LEFT, animation_duration=0.5) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert "if(lt(t,0.5)" in x - assert "-150" in x # 起始位置 = -pip_width - assert y == "200" # y 不变 + x_expr, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(lt(t,0.5)" in x_expr + assert y_expr == "200" - def test_slide_in_from_right(self): - """从右侧滑入.""" + def test_slide_right_enter(self): layer = _make_layer(animation_in=ANIMATION_SLIDE_RIGHT, animation_duration=0.5) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert str(OUTPUT_W) in x - assert y == "200" + x_expr, _ = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "output_width" not in x_expr # 应该是具体数值 + assert "if(lt(t,0.5)" in x_expr + assert "1920" in x_expr - def test_slide_in_from_top(self): - """从顶部滑入.""" - layer = _make_layer(animation_in=ANIMATION_SLIDE_TOP, animation_duration=0.3) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert "if(lt(t,0.3)" in y - assert "-100" in y + def test_slide_top_enter(self): + layer = _make_layer(animation_in=ANIMATION_SLIDE_TOP, animation_duration=0.5) + x_expr, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert x_expr == "100" + assert "if(lt(t,0.5)" in y_expr - def test_slide_in_from_bottom(self): - """从底部滑入.""" - layer = _make_layer(animation_in=ANIMATION_SLIDE_BOTTOM, animation_duration=0.3) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert str(OUTPUT_H) in y + def test_slide_bottom_enter(self): + layer = _make_layer(animation_in=ANIMATION_SLIDE_BOTTOM, animation_duration=0.5) + _, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(lt(t,0.5)" in y_expr + assert "1080" in y_expr - def test_slide_out_to_left(self): - """向左滑出.""" + def test_slide_left_exit(self): layer = _make_layer( animation_out=ANIMATION_SLIDE_LEFT, animation_duration=0.5, - duration=3.0, + duration=5.0, ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert "gt(t,2.5)" in x - assert y == "200" + x_expr, _ = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(gt(t,4.5)" in x_expr - def test_slide_out_to_right(self): - """向右滑出.""" + def test_slide_right_exit(self): layer = _make_layer( animation_out=ANIMATION_SLIDE_RIGHT, animation_duration=0.5, - duration=3.0, + duration=5.0, ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert "gt(t,2.5)" in x - assert y == "200" - # 向右滑出:结束时 x > base_x(值变大) - # 检查表达式中含增大方向的计算 - assert "+(t-2.5)/0.5*" in x + x_expr, _ = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(gt(t,4.5)" in x_expr - def test_slide_out_to_top(self): - """向上滑出.""" + def test_slide_top_exit(self): layer = _make_layer( animation_out=ANIMATION_SLIDE_TOP, animation_duration=0.5, duration=5.0, ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert "gt(t,4.5)" in y + _, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(gt(t,4.5)" in y_expr - def test_slide_out_to_bottom(self): - """向下滑出.""" + def test_slide_bottom_exit(self): layer = _make_layer( animation_out=ANIMATION_SLIDE_BOTTOM, animation_duration=0.5, duration=5.0, ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert "gt(t,4.5)" in y - # 向下滑出:y 值增大 - assert "+(t-4.5)/0.5*" in y + _, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert "if(gt(t,4.5)" in y_expr - def test_slide_in_and_out_different_axes(self): - """滑入(x方向) + 滑出(y方向),两个轴都有动画.""" - layer = _make_layer( - animation_in=ANIMATION_SLIDE_LEFT, - animation_out=ANIMATION_SLIDE_BOTTOM, - animation_duration=0.5, - duration=4.0, - ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert "lt(t,0.5)" in x # x 方向入场 - assert "gt(t,3.5)" in y # y 方向出场 + def test_exit_animation_no_duration_ignored(self): + layer = _make_layer(animation_out=ANIMATION_SLIDE_LEFT, animation_duration=0.5) + x_expr, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert x_expr == "100" + assert y_expr == "200" def test_zero_animation_duration_no_effect(self): - """动画时长为 0 时无效果.""" layer = _make_layer(animation_in=ANIMATION_SLIDE_LEFT, animation_duration=0) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert y == "200" - - def test_no_duration_skip_outro(self): - """无 duration 时跳过滑出.""" - layer = _make_layer( - animation_out=ANIMATION_SLIDE_LEFT, - animation_duration=0.5, - duration=None, - ) - x, y = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x == "100" - assert y == "200" - - def test_expression_format_quoted(self): - """有动画时表达式带单引号.""" - layer = _make_layer(animation_in=ANIMATION_SLIDE_LEFT, animation_duration=0.5) - x, _ = build_overlay_expr(layer, 100, 200, 150, 100, OUTPUT_W, OUTPUT_H) - assert x.startswith("'") - assert x.endswith("'") - - def test_static_position_unquoted(self): - """无动画时纯数字,不带引号.""" - layer = _make_layer() - x, y = build_overlay_expr(layer, 50, 60, 100, 80, OUTPUT_W, OUTPUT_H) - assert x == "50" - assert y == "60" - assert "'" not in x - assert "'" not in y + x_expr, y_expr = build_overlay_expr(layer, 100, 200, 200, 150, 1920, 1080) + assert x_expr == "100" + assert y_expr == "200" -# ═══════════════════════════════════════════════════════════════════════════════ -# build_enable_expr -# ═══════════════════════════════════════════════════════════════════════════════ +# ── build_enable_expr ──────────────────────────────────────────────────────── class TestBuildEnableExpr: - """enable 表达式构建测试.""" - - def test_no_time_restriction(self): - """无时间限制返回空.""" - layer = _make_layer() + def test_no_start_no_duration_empty(self): + layer = _make_layer(start_time=0.0) + # duration默认是0.0 assert build_enable_expr(layer) == "" - def test_start_time_only(self): - """只有开始时间.""" + def test_with_start_and_duration(self): + layer = _make_layer(start_time=2.0, duration=3.0) + result = build_enable_expr(layer) + assert result == ":enable='between(t,2.0,5.0)'" + + def test_with_start_only_no_duration(self): layer = _make_layer(start_time=5.0) result = build_enable_expr(layer) assert result == ":enable='gte(t,5.0)'" - def test_duration_only(self): - """只有 duration(从 0 开始).""" - layer = _make_layer(duration=10.0) - result = build_enable_expr(layer) - assert result == ":enable='between(t,0.0,10.0)'" - - def test_start_and_duration(self): - """开始时间 + 时长.""" - layer = _make_layer(start_time=2.0, duration=5.0) - result = build_enable_expr(layer) - assert "between(t,2.0,7.0)" in result - - def test_zero_start_with_duration(self): - """0 开始 + 时长.""" - layer = _make_layer(start_time=0, duration=3.5) - result = build_enable_expr(layer) - assert "between(t,0.0,3.5)" in result - def test_negative_start_clamped(self): - """负开始时间钳制为 0.""" layer = _make_layer(start_time=-1.0, duration=5.0) result = build_enable_expr(layer) - assert "between(t,0.0,5.0)" in result + assert "between(t,0.0," in result - def test_none_duration(self): - """duration=None 视为无限.""" - layer = _make_layer(start_time=3.0, duration=None) + def test_zero_duration_with_start(self): + layer = _make_layer(start_time=3.0, duration=0.0) result = build_enable_expr(layer) assert "gte(t,3.0)" in result - assert "between" not in result + + def test_zero_start_and_duration(self): + layer = _make_layer(start_time=0, duration=0) + assert build_enable_expr(layer) == "" -# ═══════════════════════════════════════════════════════════════════════════════ -# build_pip_filters -# ═══════════════════════════════════════════════════════════════════════════════ +# ── build_pip_filters ─────────────────────────────────────────────────────── class TestBuildPipFilters: - """完整滤镜链构建测试.""" - def test_empty_layers(self): - """空图层列表返回空.""" - filters, inputs, label = build_pip_filters( - "base", - [], - [], - output_width=OUTPUT_W, - output_height=OUTPUT_H, - ) - assert filters == [] - assert inputs == [] - assert label == "base" + filter_parts, input_args, final = build_pip_filters("base", [], [], output_width=1920, output_height=1080) + assert filter_parts == [] + assert input_args == [] + assert final == "base" def test_single_layer(self): - """单个图层.""" - layer = _make_layer(width="20%", position="bottom_right") - path = Path("/tmp/clip1.mp4") - - filters, inputs, label = build_pip_filters( - "v0", - [layer], - [path], - output_width=OUTPUT_W, - output_height=OUTPUT_H, + layer = _make_layer(width="200", height="150", position="top_left", source="test.mp4") + filter_parts, input_args, final = build_pip_filters( + "base", [layer], ["/tmp/test.mp4"], output_width=1920, output_height=1080 ) - - # 2 个滤镜片段:预处理 + overlay - assert len(filters) == 2 - # 1 个输入 - assert inputs == ["-i", str(path)] - # 最终标签 - assert label == "pip_combined_0" + assert len(filter_parts) == 2 # pre_filter + overlay + assert input_args == ["-i", "/tmp/test.mp4"] + assert final == "pip_combined_0" def test_multiple_layers(self): - """多个图层.""" layers = [ - _make_layer(width="30%", position="bottom_left"), - _make_layer(width="25%", position="top_right"), - _make_layer(width="20%", position="top_left"), + _make_layer(width="100", height="100", position="top_left"), + _make_layer(width="100", height="100", position="top_right"), ] - paths = [Path("/tmp/a.mp4"), Path("/tmp/b.mp4"), Path("/tmp/c.mp4")] - - filters, inputs, label = build_pip_filters( - "base", - layers, - paths, - output_width=OUTPUT_W, - output_height=OUTPUT_H, + sources = ["/tmp/a.mp4", "/tmp/b.mp4"] + filter_parts, input_args, final = build_pip_filters( + "base", layers, sources, output_width=1920, output_height=1080 ) + assert len(filter_parts) == 4 # 2 pre + 2 overlay + assert len(input_args) == 4 # 2 * (-i, path) + assert final == "pip_combined_1" - # 每个图层 2 个滤镜(预处理 + overlay) - assert len(filters) == 6 - # 3 个输入 - assert len(inputs) == 6 # -i path × 3 - assert inputs[0::2] == ["-i", "-i", "-i"] - # 最终标签是最后一个 combined - assert label == "pip_combined_2" + def test_mismatched_layers_and_sources(self): + layer = _make_layer() + with pytest.raises(ValueError, match="长度不一致"): + build_pip_filters("base", [layer], [], output_width=1920, output_height=1080) - def test_base_input_idx_offset(self): - """base_input_idx 偏移.""" - layer = _make_layer(width="20%") - filters, inputs, label = build_pip_filters( + def test_custom_base_input_index(self): + layer = _make_layer(width="100", height="100", position="top_left") + filter_parts, input_args, _ = build_pip_filters( "base", [layer], - [Path("/tmp/x.mp4")], - output_width=OUTPUT_W, - output_height=OUTPUT_H, + ["/a.mp4"], + output_width=1920, + output_height=1080, base_input_idx=5, ) - # 预处理滤镜引用 [5:v] - assert "[5:v]" in filters[0] + assert "[5:v]" in filter_parts[0] + assert len(input_args) == 2 - def test_layer_count_mismatch_raises(self): - """图层和路径数量不一致时报错.""" - with pytest.raises(ValueError, match="长度不一致"): - build_pip_filters( - "base", - [_make_layer()], - [], - output_width=OUTPUT_W, - output_height=OUTPUT_H, - ) - - def test_filter_chaining(self): - """多图层时滤镜链正确串联.""" - layers = [_make_layer(width="10%"), _make_layer(width="10%")] - paths = [Path("/tmp/1.mp4"), Path("/tmp/2.mp4")] - - filters, _, _ = build_pip_filters( + def test_path_object_supported(self): + layer = _make_layer(width="100", height="100", position="top_left") + _, input_args, _ = build_pip_filters( "base", - layers, - paths, - output_width=OUTPUT_W, - output_height=OUTPUT_H, - ) - - # 第一个 overlay 的输入是 base + pip_pre_0 - # 输出是 pip_combined_0 - assert "[base]" in filters[1] - assert "[pip_combined_0]" in filters[1] - - # 第二个 overlay 的输入是 pip_combined_0 + pip_pre_1 - # 输出是 pip_combined_1 - assert "[pip_combined_0]" in filters[3] - assert "[pip_combined_1]" in filters[3] - - def test_with_animation_layer(self): - """带动画的图层生成正确表达式.""" - layer = _make_layer( - width="30%", - animation_in=ANIMATION_SLIDE_BOTTOM, - animation_duration=0.5, - ) - filters, inputs, _ = build_pip_filters( - "v0", [layer], - [Path("/tmp/a.mp4")], - output_width=OUTPUT_W, - output_height=OUTPUT_H, + [Path("/tmp/test.mp4")], + output_width=1920, + output_height=1080, ) - # overlay 滤镜中包含滑动表达式 - overlay_filter = filters[1] - assert "overlay=" in overlay_filter - assert str(OUTPUT_H) in overlay_filter # 从底部滑入 + assert input_args[1] == "/tmp/test.mp4" - def test_with_enable_time(self): - """带时间控制的图层.""" - layer = _make_layer(width="20%", start_time=2.0, duration=5.0) - filters, _, _ = build_pip_filters( - "v0", + def test_filter_parts_contain_correct_labels(self): + layer = _make_layer(width="100", height="100", position="top_left") + filter_parts, _, _ = build_pip_filters( + "base", [layer], - [Path("/tmp/a.mp4")], - output_width=OUTPUT_W, - output_height=OUTPUT_H, + ["/a.mp4"], + output_width=1920, + output_height=1080, ) - overlay_filter = filters[1] - assert "enable=" in overlay_filter - assert "between" in overlay_filter - - def test_string_paths(self): - """路径可以是字符串.""" - layer = _make_layer(width="10%") - filters, inputs, label = build_pip_filters( - "v0", - [layer], - ["/tmp/s.mp4"], - output_width=OUTPUT_W, - output_height=OUTPUT_H, - ) - assert inputs == ["-i", "/tmp/s.mp4"] - assert len(filters) == 2 + # pre filter输出 pip_pre_0 + assert "[pip_pre_0]" in filter_parts[0] + # overlay使用 pip_pre_0 作为输入 + assert "[pip_pre_0]" in filter_parts[1] + # overlay输出 pip_combined_0 + assert "[pip_combined_0]" in filter_parts[1] -# ═══════════════════════════════════════════════════════════════════════════════ -# validate_pip_layer -# ═══════════════════════════════════════════════════════════════════════════════ +# ── validate_pip_layer ────────────────────────────────────────────────────── class TestValidatePipLayer: - """配置验证测试.""" - def test_valid_layer(self): - """合法配置.""" - layer = _make_layer() - ok, err = validate_pip_layer(layer) - assert ok is True + layer = _make_layer( + source_type="asset_id", + source="asset_123", + width="25%", + position="bottom_right", + ) + valid, err = validate_pip_layer(layer) + assert valid is True assert err == "" - def test_empty_source_type(self): - """空 source_type.""" - layer = _make_layer(source_type="") - ok, err = validate_pip_layer(layer) - assert ok is False + def test_missing_source_type(self): + layer = _make_layer(source_type="", source="abc", width="25%", position="top_left") + valid, err = validate_pip_layer(layer) + assert valid is False assert "source_type" in err def test_invalid_source_type(self): - """不支持的 source_type.""" - layer = _make_layer(source_type="ftp") - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="invalid", source="abc", width="25%", position="top_left") + valid, err = validate_pip_layer(layer) + assert valid is False assert "source_type" in err - def test_empty_source(self): - """空 source.""" - layer = _make_layer(source="") - ok, err = validate_pip_layer(layer) - assert ok is False + def test_missing_source(self): + layer = _make_layer(source_type="asset_id", source="", width="25%", position="top_left") + valid, err = validate_pip_layer(layer) + assert valid is False assert "source" in err + def test_missing_width(self): + layer = _make_layer(source_type="asset_id", source="abc", width=None, position="top_left") + valid, err = validate_pip_layer(layer) + assert valid is False + assert "width" in err + + def test_empty_width(self): + layer = _make_layer(source_type="asset_id", source="abc", width="", position="top_left") + valid, err = validate_pip_layer(layer) + assert valid is False + assert "width" in err + def test_invalid_position(self): - """不支持的 position.""" - layer = _make_layer(position="middle") - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", position="invalid_pos") + valid, err = validate_pip_layer(layer) + assert valid is False assert "position" in err - def test_opacity_too_high(self): - """opacity > 1.""" - layer = _make_layer(opacity=1.5) - ok, err = validate_pip_layer(layer) - assert ok is False + def test_invalid_opacity_high(self): + layer = _make_layer(source_type="asset_id", source="abc", width="25%", opacity=2.0) + valid, err = validate_pip_layer(layer) + assert valid is False assert "opacity" in err - def test_opacity_negative(self): - """opacity < 0.""" - layer = _make_layer(opacity=-0.1) - ok, err = validate_pip_layer(layer) - assert ok is False + def test_invalid_opacity_low(self): + layer = _make_layer(source_type="asset_id", source="abc", width="25%", opacity=-0.5) + valid, err = validate_pip_layer(layer) + assert valid is False assert "opacity" in err def test_negative_corner_radius(self): - """负圆角.""" - layer = _make_layer(corner_radius=-5) - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", corner_radius=-1) + valid, err = validate_pip_layer(layer) + assert valid is False assert "corner_radius" in err def test_negative_border_width(self): - """负边框.""" - layer = _make_layer(border_width=-2) - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", border_width=-1) + valid, err = validate_pip_layer(layer) + assert valid is False assert "border_width" in err + def test_negative_animation_duration(self): + layer = _make_layer(source_type="asset_id", source="abc", width="25%", animation_duration=-1) + valid, err = validate_pip_layer(layer) + assert valid is False + assert "animation_duration" in err + def test_negative_start_time(self): - """负开始时间.""" - layer = _make_layer(start_time=-1.0) - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", start_time=-1) + valid, err = validate_pip_layer(layer) + assert valid is False assert "start_time" in err def test_negative_duration(self): - """负时长.""" - layer = _make_layer(duration=-5.0) - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", duration=-1) + valid, err = validate_pip_layer(layer) + assert valid is False assert "duration" in err def test_invalid_animation_in(self): - """不支持的入场动画.""" - layer = _make_layer(animation_in="zoom") - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", animation_in="invalid") + valid, err = validate_pip_layer(layer) + assert valid is False assert "animation_in" in err def test_invalid_animation_out(self): - """不支持的出场动画.""" - layer = _make_layer(animation_out="spin") - ok, err = validate_pip_layer(layer) - assert ok is False + layer = _make_layer(source_type="asset_id", source="abc", width="25%", animation_out="invalid") + valid, err = validate_pip_layer(layer) + assert valid is False assert "animation_out" in err - def test_multiple_errors_combined(self): - """多个错误合并.""" - layer = _make_layer(source_type="", source="", opacity=2.0, position="xxx") - ok, err = validate_pip_layer(layer) - assert ok is False - assert err.count(";") >= 2 # 至少 2 个错误 + def test_multiple_errors_joined(self): + layer = _make_layer(source_type="", source="", width=None, position="bad") + valid, err = validate_pip_layer(layer) + assert valid is False + assert err.count(";") >= 2 # 至少3个错误,2个分号 - def test_valid_url_source(self): - """URL 类型 source 合法.""" - layer = _make_layer(source_type="url", source="https://example.com/v.mp4") - ok, err = validate_pip_layer(layer) - assert ok is True + def test_all_source_types_valid(self): + for st in ("local_path", "asset_id", "url"): + layer = _make_layer(source_type=st, source="abc", width="25%") + valid, _ = validate_pip_layer(layer) + assert valid is True - def test_valid_asset_id(self): - """asset_id 类型合法.""" - layer = _make_layer(source_type="asset_id", source="asset_123") - ok, err = validate_pip_layer(layer) - assert ok is True - - def test_zero_values_valid(self): - """0 值合法(不是负数).""" - layer = _make_layer( - corner_radius=0, - border_width=0, - start_time=0, - animation_duration=0, - ) - ok, err = validate_pip_layer(layer) - assert ok is True + def test_all_positions_valid(self): + for pos in ( + "top_left", + "top_center", + "top_right", + "center_left", + "center", + "center_right", + "bottom_left", + "bottom_center", + "bottom_right", + "custom", + ): + layer = _make_layer(source_type="asset_id", source="abc", width="25%", position=pos) + valid, err = validate_pip_layer(layer) + assert valid is True, f"position {pos} should be valid: {err}" -# ═══════════════════════════════════════════════════════════════════════════════ -# count_visible_layers -# ═══════════════════════════════════════════════════════════════════════════════ +# ── count_visible_layers ──────────────────────────────────────────────────── class TestCountVisibleLayers: - """可见图层统计测试.""" - def test_all_visible(self): - """全部可见.""" - layers = [_make_layer(opacity=1.0), _make_layer(opacity=0.5)] + layers = [ + _make_layer(opacity=1.0), + _make_layer(opacity=0.5), + ] assert count_visible_layers(layers) == 2 - def test_all_invisible(self): - """全部不可见.""" - layers = [_make_layer(opacity=0.0), _make_layer(opacity=0.0)] + def test_none_visible(self): + layers = [ + _make_layer(opacity=0.0), + _make_layer(opacity=0.0), + ] assert count_visible_layers(layers) == 0 def test_mixed(self): - """混合.""" layers = [ _make_layer(opacity=1.0), _make_layer(opacity=0.0), - _make_layer(opacity=0.001), + _make_layer(opacity=0.1), + _make_layer(opacity=0.0), ] assert count_visible_layers(layers) == 2 def test_empty_list(self): - """空列表.""" assert count_visible_layers([]) == 0 + def test_negative_opacity_not_counted(self): + # opacity < 0 也不算可见 + layer = _make_layer(opacity=-0.5) + assert count_visible_layers([layer]) == 0 -# ═══════════════════════════════════════════════════════════════════════════════ -# sort_layers_by_z_index -# ═══════════════════════════════════════════════════════════════════════════════ + +# ── sort_layers_by_z_index ────────────────────────────────────────────────── class TestSortLayersByZIndex: - """图层排序测试.""" - def test_sorted_by_z_index(self): - """按 z_index 从小到大排序.""" - layers = [ - _make_layer(z_index=5, source="/tmp/a.mp4"), - _make_layer(z_index=1, source="/tmp/b.mp4"), - _make_layer(z_index=3, source="/tmp/c.mp4"), - ] - sorted_layers = sort_layers_by_z_index(layers) - assert [layer.z_index for layer in sorted_layers] == [1, 3, 5] + l1 = _make_layer(z_index=3) + l2 = _make_layer(z_index=1) + l3 = _make_layer(z_index=2) + result = sort_layers_by_z_index([l1, l2, l3]) + assert result[0].z_index == 1 + assert result[1].z_index == 2 + assert result[2].z_index == 3 def test_same_z_index_stable(self): - """相同 z_index 保持相对顺序.""" - layers = [ - _make_layer(z_index=2, source="/tmp/1.mp4"), - _make_layer(z_index=2, source="/tmp/2.mp4"), - ] - sorted_layers = sort_layers_by_z_index(layers) - assert sorted_layers[0].source == "/tmp/1.mp4" - assert sorted_layers[1].source == "/tmp/2.mp4" + l1 = _make_layer(z_index=5) + l2 = _make_layer(z_index=5) + l3 = _make_layer(z_index=5) + result = sort_layers_by_z_index([l1, l2, l3]) + # 稳定排序,保持原顺序 + assert result[0] is l1 + assert result[1] is l2 + assert result[2] is l3 + + def test_negative_z_index(self): + l1 = _make_layer(z_index=-5) + l2 = _make_layer(z_index=0) + l3 = _make_layer(z_index=5) + result = sort_layers_by_z_index([l3, l1, l2]) + assert result[0].z_index == -5 + assert result[2].z_index == 5 def test_empty_list(self): - """空列表.""" assert sort_layers_by_z_index([]) == [] def test_single_layer(self): - """单个图层.""" - layers = [_make_layer(z_index=0)] - assert len(sort_layers_by_z_index(layers)) == 1 - - def test_negative_z_index(self): - """负 z_index.""" - layers = [ - _make_layer(z_index=0, source="/tmp/0.mp4"), - _make_layer(z_index=-5, source="/tmp/-5.mp4"), - _make_layer(z_index=3, source="/tmp/3.mp4"), - ] - sorted_layers = sort_layers_by_z_index(layers) - assert [layer.z_index for layer in sorted_layers] == [-5, 0, 3] + layer = _make_layer(z_index=10) + result = sort_layers_by_z_index([layer]) + assert len(result) == 1 + assert result[0] is layer diff --git a/tests/unit/test_shared_ai_service.py b/tests/unit/test_shared_ai_service.py new file mode 100755 index 000000000..f46002dbf --- /dev/null +++ b/tests/unit/test_shared_ai_service.py @@ -0,0 +1,453 @@ +"""shared.ai_service 单元测试. + +主要测试纯逻辑部分:_parse_recommend_response / _fallback_recommend_clips / _call_ai_cover_service. +""" + +from __future__ import annotations + +import json +from unittest.mock import patch + +import pytest +from shared.ai_service import ( + _call_ai_cover_service, + _fallback_recommend_clips, + _parse_recommend_response, +) + +# ── _parse_recommend_response 测试 ──────────────────────────────────────── + + +class TestParseRecommendResponseBasic: + """基础解析测试.""" + + def test_parse_valid_json(self): + content = json.dumps( + { + "clips": [ + { + "clip_type": "intro", + "order": 0, + "text_content": "开场", + "duration": 3.0, + "transition_effect": "fade", + "asset_id": "asset1", + "start_time": 0.0, + "config": {}, + }, + { + "clip_type": "outro", + "order": 1, + "text_content": "结尾", + "duration": 2.0, + "transition_effect": "fade", + "asset_id": "", + "start_time": 0.0, + "config": {}, + }, + ], + "title": "测试视频", + "confidence": 0.85, + } + ) + result = _parse_recommend_response(content, ["asset1"], 30.0) + assert result is not None + assert len(result["clips"]) == 2 + assert result["confidence"] == 0.85 + assert result["total_duration"] == 5.0 + assert result["config"]["title"]["text"] == "测试视频" + assert result["config"]["title"]["ai_auto"] is True + + def test_parse_none_returns_none(self): + result = _parse_recommend_response(None, ["a1"], 30.0) # type: ignore[arg-type] + assert result is None + + def test_parse_empty_string_returns_none(self): + result = _parse_recommend_response("", ["a1"], 30.0) + assert result is None + + def test_parse_whitespace_only_returns_none(self): + result = _parse_recommend_response(" ", ["a1"], 30.0) + assert result is None + + def test_parse_invalid_json_returns_none(self): + result = _parse_recommend_response("not json", ["a1"], 30.0) + assert result is None + + def test_parse_non_dict_json_returns_none(self): + result = _parse_recommend_response("[1, 2, 3]", ["a1"], 30.0) + assert result is None + + +class TestParseRecommendResponseClips: + """clips 解析测试.""" + + def test_parse_no_clips_returns_none(self): + content = json.dumps({"title": "test", "clips": []}) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is None + + def test_parse_clips_not_list_returns_none(self): + content = json.dumps({"clips": "not a list"}) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is None + + def test_parse_clips_sorted_by_order(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "outro", "order": 2, "duration": 2, "asset_id": "a1"}, + {"clip_type": "intro", "order": 0, "duration": 3, "asset_id": "a1"}, + {"clip_type": "showcase", "order": 1, "duration": 5, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert len(result["clips"]) == 3 + assert result["clips"][0]["clip_type"] == "intro" + assert result["clips"][1]["clip_type"] == "showcase" + assert result["clips"][2]["clip_type"] == "outro" + + def test_parse_clips_renumbered_continuously(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 10, "duration": 2, "asset_id": "a1"}, + {"clip_type": "outro", "order": 20, "duration": 2, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["clips"][0]["order"] == 0 + assert result["clips"][1]["order"] == 1 + + def test_parse_skips_invalid_clip_dicts(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}, + "not a dict", + {"clip_type": "outro", "order": 2, "duration": 2, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert len(result["clips"]) == 2 + + +class TestParseRecommendResponseFields: + """各字段解析与边界测试.""" + + def test_parse_duration_clamped_min(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 0.5, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["clips"][0]["duration"] == 1.0 + + def test_parse_duration_clamped_max(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 100, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["clips"][0]["duration"] == 30.0 + + def test_parse_start_time_clamped_min(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1", "start_time": -5.0}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["clips"][0]["start_time"] == 0.0 + + def test_parse_asset_id_not_in_list_empty(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "unknown_asset"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1", "a2"], 30.0) + assert result is not None + assert result["clips"][0]["asset_id"] == "" + + def test_parse_asset_id_in_list_kept(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a2"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1", "a2"], 30.0) + assert result is not None + assert result["clips"][0]["asset_id"] == "a2" + + def test_parse_default_values(self): + content = json.dumps( + { + "clips": [ + {"order": 0}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + clip = result["clips"][0] + assert clip["clip_type"] == "showcase" + assert clip["text_content"] == "" + assert clip["duration"] == 3.0 + assert clip["transition_effect"] == "cut" + assert clip["asset_id"] == "" + assert clip["start_time"] == 0.0 + assert clip["config"] == {} + + +class TestParseRecommendResponseMarkdown: + """Markdown 代码块包裹的 JSON 测试.""" + + def test_parse_markdown_json(self): + content = ( + "```json\n" + + json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + "title": "md test", + } + ) + + "\n```" + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert len(result["clips"]) == 1 + assert result["config"]["title"]["text"] == "md test" + + def test_parse_backticks_no_language(self): + content = ( + "```\n" + + json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + } + ) + + "\n```" + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert len(result["clips"]) == 1 + + +class TestParseRecommendResponseConfidence: + """confidence 解析测试.""" + + def test_parse_confidence_normal(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + "confidence": 0.85, + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["confidence"] == 0.85 + + def test_parse_confidence_clamped_min(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + "confidence": -0.5, + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["confidence"] == 0.0 + + def test_parse_confidence_clamped_max(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + "confidence": 1.5, + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["confidence"] == 1.0 + + def test_parse_confidence_default(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["confidence"] == 0.7 + + +class TestParseRecommendResponseConfig: + """config 生成测试.""" + + def test_parse_no_title_no_ai_auto(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + # 没有 title 时,config 的 title.text 保持默认(DEFAULT_EDIT_PLAN_CONFIG 中的值) + assert "title" in result["config"] + + def test_parse_config_is_deep_copy(self): + content = json.dumps( + { + "clips": [{"clip_type": "intro", "order": 0, "duration": 2, "asset_id": "a1"}], + "title": "test", + } + ) + result1 = _parse_recommend_response(content, ["a1"], 30.0) + result2 = _parse_recommend_response(content, ["a1"], 30.0) + # 修改其中一个不影响另一个 + result1["config"]["title"]["text"] = "modified" + assert result2["config"]["title"]["text"] != "modified" + + +class TestParseRecommendResponseTotalDuration: + """total_duration 计算测试.""" + + def test_parse_total_duration_sum(self): + content = json.dumps( + { + "clips": [ + {"clip_type": "intro", "order": 0, "duration": 3.5, "asset_id": "a1"}, + {"clip_type": "showcase", "order": 1, "duration": 5.2, "asset_id": "a1"}, + {"clip_type": "outro", "order": 2, "duration": 2.0, "asset_id": "a1"}, + ], + } + ) + result = _parse_recommend_response(content, ["a1"], 30.0) + assert result is not None + assert result["total_duration"] == pytest.approx(10.7, abs=0.01) + + +# ── _fallback_recommend_clips 测试 ──────────────────────────────────────── + + +class TestFallbackRecommendClips: + """本地降级推荐方案测试.""" + + def test_fallback_returns_dict_with_clips(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2"], "one_take", 30.0) + assert "clips" in result + assert "config" in result + assert "total_duration" in result + assert "confidence" in result + + def test_fallback_has_intro_and_outro(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2"], "one_take", 30.0) + clips = result["clips"] + assert clips[0]["clip_type"] == "intro" + assert clips[-1]["clip_type"] == "outro" + + def test_fallback_showcase_count_matches_assets(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2", "a3"], "one_take", 30.0) + showcase_clips = [c for c in result["clips"] if c["clip_type"] == "showcase"] + assert len(showcase_clips) == 3 + + def test_fallback_no_assets_still_works(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", [], "one_take", 30.0) + assert len(result["clips"]) >= 2 # 至少有intro和outro + + def test_fallback_intro_uses_first_asset(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2"], "one_take", 30.0) + assert result["clips"][0]["asset_id"] == "a1" + + def test_fallback_outro_has_empty_asset(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1"], "one_take", 30.0) + assert result["clips"][-1]["asset_id"] == "" + + def test_fallback_confidence_in_range(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1"], "one_take", 30.0) + assert 0.75 <= result["confidence"] <= 0.95 + + def test_fallback_title_contains_asset_count(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2", "a3"], "one_take", 30.0) + assert "3" in result["config"]["title"]["text"] + assert result["config"]["title"]["ai_auto"] is True + + def test_fallback_total_duration_matches(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2"], "one_take", 30.0) + total = sum(c["duration"] for c in result["clips"]) + assert result["total_duration"] == round(total, 1) + + def test_fallback_orders_are_sequential(self): + with patch("shared.ai_service.time.sleep"): + result = _fallback_recommend_clips("plan1", "tmpl1", ["a1", "a2", "a3"], "one_take", 30.0) + orders = [c["order"] for c in result["clips"]] + assert orders == list(range(len(result["clips"]))) + + +# ── _call_ai_cover_service 测试 ─────────────────────────────────────────── + + +class TestAiCoverService: + """AI封面生成服务测试.""" + + def test_cover_type_upload(self): + with patch("shared.ai_service.time.sleep"): + result = _call_ai_cover_service("plan1", ["a1"], "upload") + assert result["type"] == "upload" + assert result["image_url"] == "" + + def test_cover_type_manual_with_frame_time(self): + with patch("shared.ai_service.time.sleep"): + result = _call_ai_cover_service("plan1", ["a1"], "manual", frame_time=5.5) + assert result["type"] == "manual" + assert result["frame_time"] == 5.5 + assert "5.5" in result["image_url"] + + def test_cover_type_ai_frame(self): + with patch("shared.ai_service.time.sleep"): + with patch("shared.ai_service.random.uniform", side_effect=[5.0, 0.9]): + result = _call_ai_cover_service("plan1", ["a1"], "ai_frame") + assert result["type"] == "ai_frame" + assert result["frame_time"] == 5.0 + assert result["confidence"] == 0.9 + assert "plan1" in result["image_url"] + + def test_cover_type_ai_regenerate(self): + with patch("shared.ai_service.time.sleep"): + result = _call_ai_cover_service("plan1", ["a1"], "ai_regenerate") + assert result["type"] == "ai_frame" + + def test_cover_frame_time_in_range(self): + with patch("shared.ai_service.time.sleep"): + result = _call_ai_cover_service("plan1", ["a1"], "ai_frame") + assert 1.0 <= result["frame_time"] <= 10.0 diff --git a/tests/unit/test_sticker_engine_pure.py b/tests/unit/test_sticker_engine_pure.py index f945f5192..805d5ff58 100755 --- a/tests/unit/test_sticker_engine_pure.py +++ b/tests/unit/test_sticker_engine_pure.py @@ -1,9 +1,6 @@ -"""贴纸引擎纯逻辑单元测试.""" +"""sticker_engine_pure 单元测试.""" -from __future__ import annotations - -import pytest -from video_processing.sticker_engine_pure import ( +from apps.worker.video_processing.sticker_engine_pure import ( build_drawtext_alpha_expr, build_enable_expr, build_image_fade_filters, @@ -29,752 +26,806 @@ from video_processing.sticker_engine_pure import ( validate_text_sticker, ) -# ───────────────────────────────────────────────────────────────────────────── -# 安全类型转换测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── safe_float ────────────────────────────────────────────────────────────────── class TestSafeFloat: - """safe_float 测试.""" + def test_none_returns_none(self): + assert safe_float(None) is None def test_int_input(self): - """整数输入.""" assert safe_float(42) == 42.0 def test_float_input(self): - """浮点数输入.""" assert safe_float(3.14) == 3.14 - def test_string_number(self): - """字符串数字.""" + def test_string_int_string(self): assert safe_float("3.14") == 3.14 - def test_string_int(self): - """字符串整数.""" + def test_string_integer_string(self): assert safe_float("100") == 100.0 - def test_none_input(self): - """None 输入.""" - assert safe_float(None) is None - def test_invalid_string(self): - """无效字符串.""" assert safe_float("abc") is None def test_empty_string(self): - """空字符串.""" assert safe_float("") is None + def test_nan_returns_none(self): + import math + + assert safe_float(float("nan")) is None + assert math.isnan(float("nan")) # 确认NaN判断生效 + + def test_negative_number(self): + assert safe_float(-5.5) == -5.5 + def test_zero(self): - """零值.""" assert safe_float(0) == 0.0 - def test_negative(self): - """负值.""" - assert safe_float(-5.5) == -5.5 + def test_boolean(self): + assert safe_float(True) == 1.0 + assert safe_float(False) == 0.0 + + +# ── safe_int ────────────────────────────────────────────────────────────────── class TestSafeInt: - """safe_int 测试.""" + def test_none_returns_default(self): + assert safe_int(None) == 0 + assert safe_int(None, default=5) == 5 def test_int_input(self): - """整数输入.""" assert safe_int(42) == 42 - def test_float_input(self): - """浮点数输入(截断).""" + def test_float_input_truncates(self): assert safe_int(3.7) == 3 + assert safe_int(3.2) == 3 - def test_string_number(self): - """字符串数字.""" - assert safe_int("42") == 42 + def test_string_integer(self): + assert safe_int("100") == 100 - def test_none_input(self): - """None 输入用默认值.""" - assert safe_int(None) == 0 + def test_string_float(self): + assert safe_int("3.9") == 3 - def test_none_custom_default(self): - """None 输入自定义默认值.""" - assert safe_int(None, default=10) == 10 - - def test_invalid_string(self): - """无效字符串.""" + def test_invalid_string_returns_default(self): assert safe_int("abc") == 0 + assert safe_int("abc", default=-1) == -1 - def test_negative(self): - """负值.""" - assert safe_int(-5) == -5 + def test_empty_string(self): + assert safe_int("") == 0 + + def test_negative_number(self): + assert safe_int(-10) == -10 def test_zero(self): - """零值.""" assert safe_int(0) == 0 + def test_boolean(self): + assert safe_int(True) == 1 + assert safe_int(False) == 0 + + +# ── safe_bool ──────────────────────────────────────────────────────────────── + class TestSafeBool: - """safe_bool 测试.""" - - def test_true_bool(self): - """True.""" + def test_boolean_passthrough(self): assert safe_bool(True) is True - - def test_false_bool(self): - """False.""" assert safe_bool(False) is False - def test_none(self): - """None -> False.""" + def test_none_returns_false(self): assert safe_bool(None) is False - def test_string_true(self): - """字符串 true.""" + def test_string_true_variants(self): assert safe_bool("true") is True - - def test_string_yes(self): - """字符串 yes.""" - assert safe_bool("yes") is True - - def test_string_one(self): - """字符串 1.""" + assert safe_bool("True") is True + assert safe_bool("TRUE") is True assert safe_bool("1") is True + assert safe_bool("yes") is True + assert safe_bool("YES") is True + assert safe_bool("on") is True + assert safe_bool("On") is True - def test_string_false(self): - """字符串 false.""" + def test_string_false_variants(self): assert safe_bool("false") is False + assert safe_bool("0") is False + assert safe_bool("no") is False + assert safe_bool("off") is False - def test_int_one(self): - """整数 1 -> True.""" + def test_numeric_values(self): assert safe_bool(1) is True - - def test_int_zero(self): - """整数 0 -> False.""" assert safe_bool(0) is False + assert safe_bool(-1) is True - def test_empty_list(self): - """空列表 -> False.""" + def test_empty_string(self): + assert safe_bool("") is False + + def test_list_truthy_falsy(self): + assert safe_bool([1]) is True assert safe_bool([]) is False -# ───────────────────────────────────────────────────────────────────────────── -# 尺寸估算测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── estimate_sticker_size ──────────────────────────────────────────────── class TestEstimateStickerSize: - """贴纸尺寸估算测试.""" - def test_default_scale(self): - """默认 scale=1.0.""" - w, h = estimate_sticker_size(1000, 1000) - assert w == 300 # 1000 * 0.3 * 1.0 - assert h == 300 + w, h = estimate_sticker_size(1000, 800) + assert w == 300 # 1000 * 0.3 + assert h == 240 # 800 * 0.3 def test_custom_scale(self): - """自定义缩放.""" - w, h = estimate_sticker_size(1000, 1000, scale=0.5) - assert w == 150 + w, h = estimate_sticker_size(1000, 800, scale=2.0) + assert w == 600 + assert h == 480 + + def test_fixed_width_and_height(self): + w, h = estimate_sticker_size(1000, 800, fixed_width=200, fixed_height=150) + assert w == 200 assert h == 150 - def test_fixed_width_height(self): - """固定宽高.""" - w, h = estimate_sticker_size(1000, 1000, fixed_width=200, fixed_height=100) - assert w == 200 - assert h == 100 + def test_fixed_width_only(self): + w, h = estimate_sticker_size(1000, 800, fixed_width=500) + assert w == 500 + assert h == 240 # 仍然按比例算高 - def test_scale_2x(self): - """2倍缩放.""" - w, h = estimate_sticker_size(800, 600, scale=2.0) - assert w == 480 # 800 * 0.3 * 2 - assert h == 360 # 600 * 0.3 * 2 + def test_fixed_height_only(self): + w, h = estimate_sticker_size(1000, 800, fixed_height=400) + assert w == 300 + assert h == 400 + + def test_minimum_size(self): + w, h = estimate_sticker_size(1, 1, scale=0.01) + assert w >= 1 + assert h >= 1 def test_zero_canvas(self): - """零画布尺寸,返回最小 1.""" w, h = estimate_sticker_size(0, 0) assert w >= 1 assert h >= 1 + def test_scale_zero(self): + w, h = estimate_sticker_size(1000, 800, scale=0) + assert w >= 1 + assert h >= 1 + + +# ── estimate_text_size ────────────────────────────────────────────── + class TestEstimateTextSize: - """文字尺寸估算测试.""" - def test_normal_text(self): - """普通文字.""" - w, h = estimate_text_size("Hello", 36) - assert w == int(5 * 36 * 0.6) - assert h == int(36 * 1.4) + w, h = estimate_text_size("hello", 20) + assert w == int(5 * 20 * 0.6) + assert h == int(20 * 1.4) def test_empty_text(self): - """空文字.""" - w, h = estimate_text_size("", 36) + w, h = estimate_text_size("", 20) assert w == 0 assert h == 0 - def test_large_font(self): - """大字号.""" - w, h = estimate_text_size("A", 72) - assert w == int(1 * 72 * 0.6) - assert h == int(72 * 1.4) + def test_chinese_text(self): + w, h = estimate_text_size("你好世界", 30) + assert w == int(4 * 30 * 0.6) + assert h == int(30 * 1.4) - def test_chinese_chars(self): - """中文字符.""" - w, h = estimate_text_size("你好世界", 48) - assert w == int(4 * 48 * 0.6) - assert h == int(48 * 1.4) + def test_minimum_size(self): + w, h = estimate_text_size("a", 1) + assert w >= 1 + assert h >= 1 + + def test_single_char(self): + w, h = estimate_text_size("x", 100) + assert w == int(1 * 100 * 0.6) + assert h == int(100 * 1.4) -# ───────────────────────────────────────────────────────────────────────────── -# 时间计算测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── calculate_fade_out_start ──────────────────────────────────────── class TestCalculateFadeOutStart: - """淡出开始时间计算测试.""" - def test_normal_case(self): - """正常情况.""" - assert calculate_fade_out_start(10, 30, 2) == pytest.approx(38.0) + assert calculate_fade_out_start(10, 20, 3) == 27.0 # 10 + 20 - 3 - def test_no_fade_out(self): - """无淡出.""" - assert calculate_fade_out_start(10, 30, 0) == 0.0 - - def test_negative_fade_out(self): - """负淡出.""" - assert calculate_fade_out_start(10, 30, -1) == 0.0 + def test_zero_fade_out(self): + assert calculate_fade_out_start(10, 20, 0) == 0.0 def test_zero_duration(self): - """零时长.""" - assert calculate_fade_out_start(10, 0, 2) == 0.0 + assert calculate_fade_out_start(10, 0, 3) == 0.0 - def test_fade_out_longer_than_duration(self): - """淡出超过时长,返回 0.""" - # start=10, dur=5, fade=10 -> 10+5-10 = 5 > 0 - assert calculate_fade_out_start(10, 5, 10) == pytest.approx(5.0) + def test_negative_fade_out(self): + assert calculate_fade_out_start(10, 20, -1) == 0.0 - def test_fade_out_starts_before_zero(self): - """淡出开始时间在 0 之前,钳制到 0.""" - # start=0, dur=3, fade=5 -> 0+3-5 = -2 -> 0 - assert calculate_fade_out_start(0, 3, 5) == 0.0 + def test_fade_longer_than_duration(self): + result = calculate_fade_out_start(5, 3, 10) + assert result == 0.0 # max(0, 5+3-10) = max(0, -2) = 0 + + def test_start_at_zero(self): + assert calculate_fade_out_start(0, 10, 2) == 8.0 + + def test_float_values(self): + assert calculate_fade_out_start(1.5, 5.5, 2.0) == 5.0 + + +# ── calculate_end_time ──────────────────────────────────────────── class TestCalculateEndTime: - """结束时间计算测试.""" - def test_normal_case(self): - """正常情况.""" - assert calculate_end_time(10, 30) == 40.0 + assert calculate_end_time(10, 5) == 15.0 def test_zero_duration(self): - """零时长.""" assert calculate_end_time(10, 0) == 10.0 def test_negative_duration(self): - """负时长.""" assert calculate_end_time(10, -5) == 10.0 - def test_zero_start(self): - """零开始.""" - assert calculate_end_time(0, 100) == 100.0 + def test_start_at_zero(self): + assert calculate_end_time(0, 10) == 10.0 + + def test_float_values(self): + assert calculate_end_time(1.5, 2.5) == 4.0 + + +# ── has_time_range ────────────────────────────────────────────── class TestHasTimeRange: - """时间范围判断测试.""" - def test_positive_duration(self): - """正时长.""" - assert has_time_range(30) is True + assert has_time_range(10) is True + assert has_time_range(0.1) is True def test_zero_duration(self): - """零时长.""" assert has_time_range(0) is False def test_negative_duration(self): - """负时长.""" assert has_time_range(-5) is False -# ───────────────────────────────────────────────────────────────────────────── -# 滤镜构建测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── build_scale_filter ──────────────────────────────────────── class TestBuildScaleFilter: - """缩放滤镜构建测试.""" - def test_fixed_width_height(self): - """固定宽高.""" - result = build_scale_filter(width=200, height=100) - assert result == "scale=200:100" + assert build_scale_filter(width=100, height=200) == "scale=100:200" def test_scale_only(self): - """仅缩放.""" - result = build_scale_filter(scale=0.5) - assert result == "scale=iw*0.5:ih*0.5" + assert build_scale_filter(scale=0.5) == "scale=iw*0.5:ih*0.5" - def test_no_scaling_needed(self): - """无需缩放.""" - result = build_scale_filter(scale=1.0) - assert result is None + def test_default_no_scale(self): + assert build_scale_filter() is None + assert build_scale_filter(scale=1.0) is None - def test_scale_2x(self): - """2倍缩放.""" - result = build_scale_filter(scale=2.0) - assert result == "scale=iw*2.0:ih*2.0" + def test_width_only_returns_none(self): + # 只有width没有height,且scale=1.0,返回None + assert build_scale_filter(width=100) is None - def test_fixed_overrides_scale(self): - """固定宽高优先于 scale.""" - result = build_scale_filter(width=100, height=50, scale=0.5) - assert result == "scale=100:50" + def test_height_only_returns_none(self): + assert build_scale_filter(height=200) is None + + def test_scale_with_width_height_overrides_scale(self): + # width和height都有时优先 + assert build_scale_filter(width=100, height=200, scale=0.5) == "scale=100:200" + + +# ── build_opacity_filter ────────────────────────────────────── class TestBuildOpacityFilter: - """透明度滤镜构建测试.""" + def test_full_opacity(self): + assert build_opacity_filter(1.0) is None + assert build_opacity_filter(1.5) is None # 大于1也返回None def test_partial_opacity(self): - """部分透明.""" - result = build_opacity_filter(0.5) - assert result == "colorchannelmixer=aa=0.5" + assert build_opacity_filter(0.5) == "colorchannelmixer=aa=0.5" - def test_fully_opaque(self): - """完全不透明.""" - result = build_opacity_filter(1.0) - assert result is None + def test_zero_opacity(self): + assert build_opacity_filter(0.0) == "colorchannelmixer=aa=0.0" - def test_fully_transparent(self): - """完全透明.""" - result = build_opacity_filter(0.0) - assert result == "colorchannelmixer=aa=0.0" + def test_negative_clamped(self): + assert build_opacity_filter(-0.5) == "colorchannelmixer=aa=0.0" - def test_opacity_above_1_clamped(self): - """超过 1 被钳制.""" - result = build_opacity_filter(1.5) - assert result is None + def test_above_one_clamped(self): + # 大于1的情况:>=1.0返回None + assert build_opacity_filter(2.0) is None - def test_opacity_below_0_clamped(self): - """低于 0 被钳制.""" - result = build_opacity_filter(-0.5) - assert result == "colorchannelmixer=aa=0.0" + +# ── build_image_fade_filters ──────────────────────────────────── class TestBuildImageFadeFilters: - """图片淡入淡出滤镜测试.""" + def test_no_fade(self): + assert build_image_fade_filters(10, 20) == [] def test_fade_in_only(self): - """仅淡入.""" - result = build_image_fade_filters(10, 30, fade_in=1.0) + result = build_image_fade_filters(10, 20, fade_in=2) assert len(result) == 1 - assert "fade=in:st=10:d=1.0:alpha=1" in result[0] + assert "fade=in:st=10:d=2:alpha=1" in result[0] def test_fade_out_only(self): - """仅淡出.""" - result = build_image_fade_filters(10, 30, fade_out=2.0) + result = build_image_fade_filters(10, 20, fade_out=3) assert len(result) == 1 - assert "fade=out" in result[0] - assert "st=38.0" in result[0] # 10 + 30 - 2 = 38 + assert "fade=out:st=27:d=3:alpha=1" in result[0] - def test_fade_in_and_out(self): - """淡入+淡出.""" - result = build_image_fade_filters(0, 10, fade_in=1.0, fade_out=1.0) + def test_both_fades(self): + result = build_image_fade_filters(10, 20, fade_in=2, fade_out=3) assert len(result) == 2 assert "fade=in" in result[0] assert "fade=out" in result[1] - def test_no_fade(self): - """无淡入淡出.""" - result = build_image_fade_filters(10, 30) - assert len(result) == 0 + def test_fade_out_zero_duration_skipped(self): + result = build_image_fade_filters(10, 0, fade_out=3) + assert result == [] - def test_zero_duration_no_fade_out(self): - """零时长不生成淡出.""" - result = build_image_fade_filters(10, 0, fade_out=1.0) - assert len(result) == 0 + def test_fade_out_negative_duration(self): + result = build_image_fade_filters(10, -5, fade_out=3) + assert result == [] + + +# ── build_enable_expr ──────────────────────────────────────── class TestBuildEnableExpr: - """enable 表达式构建测试.""" - - def test_normal_duration(self): - """正常时长.""" - result = build_enable_expr(10, 30) - assert "between(t,10,40" in result - assert "enable" in result + def test_positive_duration(self): + result = build_enable_expr(10, 5) + assert result == ":enable='between(t,10,15)'" def test_zero_duration(self): - """零时长返回空.""" - result = build_enable_expr(10, 0) - assert result == "" + assert build_enable_expr(10, 0) == "" def test_negative_duration(self): - """负时长返回空.""" - result = build_enable_expr(10, -5) - assert result == "" + assert build_enable_expr(10, -1) == "" - def test_zero_start(self): - """从零开始.""" - result = build_enable_expr(0, 100) - assert "t,0,100" in result + def test_start_at_zero(self): + result = build_enable_expr(0, 10) + assert result == ":enable='between(t,0,10)'" + + def test_float_values(self): + result = build_enable_expr(1.5, 2.5) + assert "between(t,1.5,4.0)" in result -# ───────────────────────────────────────────────────────────────────────────── -# drawtext 相关测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── escape_drawtext_text ────────────────────────────────────── class TestEscapeDrawtextText: - """文字转义测试.""" - def test_no_special_chars(self): - """无特殊字符.""" - assert escape_drawtext_text("Hello") == "Hello" + assert escape_drawtext_text("hello") == "hello" def test_colon_escaped(self): - """冒号转义.""" - assert escape_drawtext_text("a:b") == "a\\:b" + assert escape_drawtext_text("a:b:c") == "a\\:b\\:c" - def test_quote_escaped(self): - """单引号转义.""" - assert escape_drawtext_text("it's") == "it\\'s" + def test_single_quote_escaped(self): + assert escape_drawtext_text("a'b'c") == "a\\'b\\'c" - def test_multiple_special_chars(self): - """多个特殊字符.""" - assert escape_drawtext_text("a:b:c'd") == "a\\:b\\:c\\'d" + def test_both_special_chars(self): + result = escape_drawtext_text("it's: test") + assert result == "it\\'s\\: test" def test_empty_string(self): - """空字符串.""" assert escape_drawtext_text("") == "" + def test_backslash_not_escaped(self): + # 只转义冒号和单引号 + assert escape_drawtext_text("a\\b") == "a\\b" + + +# ── build_drawtext_alpha_expr ────────────────────────────────── + class TestBuildDrawtextAlphaExpr: - """drawtext alpha 表达式测试.""" - def test_no_fade(self): - """无淡入淡出.""" - assert build_drawtext_alpha_expr(10, 30) == "1" + assert build_drawtext_alpha_expr(10, 20) == "1" def test_fade_in_only(self): - """仅淡入.""" - result = build_drawtext_alpha_expr(10, 30, fade_in=2.0) - assert "if(lt(t,12.0)" in result - assert "(t-10)/2.0" in result + result = build_drawtext_alpha_expr(10, 20, fade_in=2) + assert result == "if(lt(t,12),(t-10)/2,1)" def test_fade_out_only(self): - """仅淡出.""" - result = build_drawtext_alpha_expr(10, 30, fade_out=3.0) - assert "if(gt(t,37" in result - assert "-t)/3.0" in result + result = build_drawtext_alpha_expr(10, 20, fade_out=3) + assert result == "if(gt(t,27),(30-t)/3,1)" - def test_fade_in_and_out(self): - """淡入+淡出(相乘).""" - result = build_drawtext_alpha_expr(0, 10, fade_in=1.0, fade_out=1.0) - assert "*" in result - assert result.count("if(") == 2 + def test_both_fades(self): + result = build_drawtext_alpha_expr(10, 20, fade_in=2, fade_out=3) + assert "if(lt(t," in result + assert "if(gt(t," in result + assert result.count("*") == 1 # 两部分相乘 - def test_zero_duration_no_fade_out(self): - """零时长不生成淡出.""" - result = build_drawtext_alpha_expr(10, 0, fade_out=1.0) + def test_fade_out_zero_duration(self): + result = build_drawtext_alpha_expr(10, 0, fade_out=3) + assert result == "1" + + def test_zero_fade_in(self): + result = build_drawtext_alpha_expr(10, 20, fade_in=0) assert result == "1" +# ── build_stroke_params ────────────────────────────────────── + + class TestBuildStrokeParams: - """描边参数测试.""" - def test_no_stroke(self): - """无描边.""" - result = build_stroke_params(0) - assert len(result) == 0 + assert build_stroke_params() == [] + assert build_stroke_params(stroke_width=0) == [] + assert build_stroke_params(stroke_width=-1) == [] - def test_with_stroke(self): - """有描边.""" - result = build_stroke_params(2, "red") + def test_default_color(self): + result = build_stroke_params(stroke_width=2) assert len(result) == 2 assert "borderw=2" in result + assert "bordercolor=black" in result + + def test_custom_color(self): + result = build_stroke_params(stroke_width=3, stroke_color="red") + assert "borderw=3" in result assert "bordercolor=red" in result - def test_negative_width(self): - """负宽度.""" - result = build_stroke_params(-1) - assert len(result) == 0 + +# ── build_shadow_params ────────────────────────────────────── class TestBuildShadowParams: - """阴影参数测试.""" - def test_no_shadow(self): - """无阴影.""" - result = build_shadow_params(0) - assert len(result) == 0 + assert build_shadow_params() == [] + assert build_shadow_params(shadow_alpha=0) == [] + assert build_shadow_params(shadow_alpha=-1) == [] - def test_with_shadow(self): - """有阴影.""" - result = build_shadow_params(0.5, 3, 4, "black") + def test_default_values(self): + result = build_shadow_params(shadow_alpha=0.5) assert len(result) == 3 - assert "shadowx=3" in result - assert "shadowy=4" in result + assert "shadowx=2" in result + assert "shadowy=2" in result assert "shadowcolor=black@0.5" in result - def test_shadow_alpha_clamped(self): - """透明度钳制.""" - result = build_shadow_params(1.5) - assert "shadowcolor=black@1.0" in result[2] + def test_custom_offset(self): + result = build_shadow_params(shadow_alpha=0.3, shadow_x=5, shadow_y=7, shadow_color="red") + assert "shadowx=5" in result + assert "shadowy=7" in result + assert "shadowcolor=red@0.3" in result + + def test_alpha_clamped(self): + result = build_shadow_params(shadow_alpha=1.5) + assert "shadowcolor=black@1.0" in result + + def test_alpha_negative_clamped_to_zero(self): + # 负数会触发<=0分支,返回空列表 + assert build_shadow_params(shadow_alpha=-0.5) == [] -# ───────────────────────────────────────────────────────────────────────────── -# 贴纸排序与过滤测试 -# ───────────────────────────────────────────────────────────────────────────── +# ── sort_stickers_by_z_index ──────────────────────────────────── class TestSortStickersByZIndex: - """贴纸排序测试.""" - def test_sorted_by_z_index(self): - """按 z_index 排序.""" stickers = [ - {"z_index": 20, "name": "top"}, - {"z_index": 5, "name": "bottom"}, - {"z_index": 10, "name": "middle"}, + {"name": "c", "z_index": 3}, + {"name": "a", "z_index": 1}, + {"name": "b", "z_index": 2}, ] result = sort_stickers_by_z_index(stickers) - assert result[0]["name"] == "bottom" - assert result[1]["name"] == "middle" - assert result[2]["name"] == "top" + assert [s["name"] for s in result] == ["a", "b", "c"] - def test_same_z_index_preserves_order(self): - """相同 z_index 保持原顺序.""" + def test_missing_z_index_defaults_to_10(self): stickers = [ - {"z_index": 10, "name": "first"}, - {"z_index": 10, "name": "second"}, + {"name": "low", "z_index": 5}, + {"name": "no_z"}, # 默认10 + {"name": "high", "z_index": 15}, ] result = sort_stickers_by_z_index(stickers) - assert result[0]["name"] == "first" - assert result[1]["name"] == "second" + assert [s["name"] for s in result] == ["low", "no_z", "high"] + + def test_same_z_index_stable(self): + stickers = [ + {"name": "first", "z_index": 5}, + {"name": "second", "z_index": 5}, + {"name": "third", "z_index": 5}, + ] + result = sort_stickers_by_z_index(stickers) + assert [s["name"] for s in result] == ["first", "second", "third"] def test_empty_list(self): - """空列表.""" assert sort_stickers_by_z_index([]) == [] - def test_default_z_index_10(self): - """无 z_index 默认 10.""" + def test_negative_z_index(self): stickers = [ - {"z_index": 5, "name": "low"}, - {"name": "default"}, + {"name": "neg", "z_index": -5}, + {"name": "zero", "z_index": 0}, + {"name": "pos", "z_index": 5}, ] result = sort_stickers_by_z_index(stickers) - assert result[0]["name"] == "low" - assert result[1]["name"] == "default" + assert [s["name"] for s in result] == ["neg", "zero", "pos"] + + def test_original_not_modified(self): + stickers = [{"z_index": 3}, {"z_index": 1}] + original = list(stickers) + sort_stickers_by_z_index(stickers) + assert stickers == original + + +# ── filter_enabled_stickers ──────────────────────────────────── class TestFilterEnabledStickers: - """启用贴纸过滤测试.""" - def test_all_enabled(self): - """全部启用.""" - stickers = [{"enabled": True}, {"enabled": True}] - assert len(filter_enabled_stickers(stickers)) == 2 - - def test_mixed(self): - """混合.""" stickers = [ - {"enabled": True, "name": "a"}, - {"enabled": False, "name": "b"}, - {"enabled": True, "name": "c"}, + {"name": "a", "enabled": True}, + {"name": "b"}, # 默认True ] result = filter_enabled_stickers(stickers) assert len(result) == 2 - assert result[0]["name"] == "a" - def test_default_enabled(self): - """默认启用.""" - stickers = [{"name": "a"}] + def test_mixed_enabled(self): + stickers = [ + {"name": "a", "enabled": True}, + {"name": "b", "enabled": False}, + {"name": "c"}, + ] result = filter_enabled_stickers(stickers) - assert len(result) == 1 + assert len(result) == 2 + assert [s["name"] for s in result] == ["a", "c"] + + def test_all_disabled(self): + stickers = [ + {"name": "a", "enabled": False}, + {"name": "b", "enabled": "false"}, + ] + result = filter_enabled_stickers(stickers) + assert len(result) == 0 def test_empty_list(self): - """空列表.""" assert filter_enabled_stickers([]) == [] + def test_string_enabled_values(self): + stickers = [ + {"name": "a", "enabled": "true"}, + {"name": "b", "enabled": "yes"}, + {"name": "c", "enabled": "0"}, + ] + result = filter_enabled_stickers(stickers) + assert [s["name"] for s in result] == ["a", "b"] + + +# ── count_sticker_types ──────────────────────────────────────── + class TestCountStickerTypes: - """贴纸类型统计测试.""" - - def test_mixed_types(self): - """混合类型.""" + def test_multiple_types(self): stickers = [ {"type": "image"}, {"type": "text"}, {"type": "image"}, + {"type": "image"}, + {"type": "emoji"}, ] - counts = count_sticker_types(stickers) - assert counts["image"] == 2 - assert counts["text"] == 1 + result = count_sticker_types(stickers) + assert result == {"image": 3, "text": 1, "emoji": 1} - def test_default_type(self): - """默认 image.""" - stickers = [{}] - counts = count_sticker_types(stickers) - assert counts["image"] == 1 + def test_default_type_image(self): + stickers = [ + {"name": "a"}, # 无type字段 + {"type": "text"}, + ] + result = count_sticker_types(stickers) + assert result == {"image": 1, "text": 1} def test_empty_list(self): - """空列表.""" assert count_sticker_types([]) == {} + def test_single_type(self): + stickers = [{"type": "text"} for _ in range(5)] + result = count_sticker_types(stickers) + assert result == {"text": 5} -# ───────────────────────────────────────────────────────────────────────────── -# overlay 相关测试 -# ───────────────────────────────────────────────────────────────────────────── + +# ── build_overlay_position ────────────────────────────────────── class TestBuildOverlayPosition: - """overlay 位置构建测试.""" - - def test_integer_position(self): - """整数位置.""" + def test_integer_values(self): assert build_overlay_position(100, 200) == "100:200" - def test_float_position_rounded(self): - """浮点取整.""" - assert build_overlay_position(100.6, 200.4) == "101:200" + def test_float_values_rounded(self): + assert build_overlay_position(100.6, 200.3) == "101:200" - def test_zero_position(self): - """零位置.""" + def test_negative_values(self): + assert build_overlay_position(-10, -20) == "-10:-20" + + def test_zero_values(self): assert build_overlay_position(0, 0) == "0:0" - def test_negative_position(self): - """负位置.""" - assert build_overlay_position(-10, -20) == "-10:-20" + +# ── build_pre_filter_label ───────────────────────────────────── class TestBuildPreFilterLabel: - """预处理标签构建测试.""" - - def test_normal_idx(self): - """正常索引.""" - assert build_pre_filter_label(3) == "sticker_3_scaled" - - def test_zero_idx(self): - """零索引.""" + def test_index_zero(self): assert build_pre_filter_label(0) == "sticker_0_scaled" + def test_positive_index(self): + assert build_pre_filter_label(5) == "sticker_5_scaled" -# ───────────────────────────────────────────────────────────────────────────── -# 验证函数测试 -# ───────────────────────────────────────────────────────────────────────────── + def test_large_index(self): + assert build_pre_filter_label(999) == "sticker_999_scaled" + + +# ── validate_image_sticker ────────────────────────────────── class TestValidateImageSticker: - """图片贴纸验证测试.""" - def test_valid_with_image_path(self): - """有 image_path,合法.""" - ok, errors = validate_image_sticker({"image_path": "/a.png"}) - assert ok is True - assert len(errors) == 0 + valid, errors = validate_image_sticker({"image_path": "/path/to/img.png"}) + assert valid is True + assert errors == [] def test_valid_with_asset_id(self): - """有 asset_id,合法.""" - ok, errors = validate_image_sticker({"asset_id": "123"}) - assert ok is True + valid, errors = validate_image_sticker({"asset_id": "asset_123"}) + assert valid is True + assert errors == [] - def test_missing_image_source(self): - """缺图片来源.""" - ok, errors = validate_image_sticker({}) - assert ok is False - assert any("image_path" in e or "asset_id" in e for e in errors) + def test_missing_image_and_asset(self): + valid, errors = validate_image_sticker({}) + assert valid is False + assert "image_path 或 asset_id" in errors[0] - def test_opacity_out_of_range(self): - """透明度超范围.""" - ok, errors = validate_image_sticker( + def test_invalid_opacity_high(self): + valid, errors = validate_image_sticker( { - "image_path": "/a.png", + "image_path": "a.png", "opacity": 1.5, } ) - assert ok is False + assert valid is False assert any("opacity" in e for e in errors) - def test_negative_scale(self): - """负缩放.""" - ok, errors = validate_image_sticker( + def test_invalid_opacity_low(self): + valid, errors = validate_image_sticker( { - "image_path": "/a.png", - "scale": -0.5, + "image_path": "a.png", + "opacity": -0.5, } ) - assert ok is False + assert valid is False + assert any("opacity" in e for e in errors) + + def test_valid_opacity_boundary(self): + valid, _ = validate_image_sticker({"image_path": "a.png", "opacity": 0}) + assert valid is True + valid, _ = validate_image_sticker({"image_path": "a.png", "opacity": 1}) + assert valid is True + + def test_invalid_scale_zero(self): + valid, errors = validate_image_sticker( + { + "image_path": "a.png", + "scale": 0, + } + ) + assert valid is False assert any("scale" in e for e in errors) - def test_negative_duration(self): - """负时长.""" - ok, errors = validate_image_sticker( + def test_invalid_scale_negative(self): + valid, errors = validate_image_sticker( { - "image_path": "/a.png", - "duration": -10, + "image_path": "a.png", + "scale": -1, } ) - assert ok is False - assert any("duration" in e for e in errors) + assert valid is False - def test_multiple_errors(self): - """多个错误.""" - ok, errors = validate_image_sticker( + def test_invalid_duration_negative(self): + valid, errors = validate_image_sticker( { - "opacity": 1.5, - "duration": -1, - "start_time": -5, - } - ) - assert ok is False - assert len(errors) >= 3 - - -class TestValidateTextSticker: - """文字贴纸验证测试.""" - - def test_valid(self): - """合法配置.""" - ok, errors = validate_text_sticker( - { - "text": "Hello", - "font_size": 36, - "font_color": "white", - } - ) - assert ok is True - assert len(errors) == 0 - - def test_empty_text(self): - """空文字.""" - ok, errors = validate_text_sticker({"text": ""}) - assert ok is False - assert any("text" in e for e in errors) - - def test_zero_font_size(self): - """零字号.""" - ok, errors = validate_text_sticker( - { - "text": "Hi", - "font_size": 0, - } - ) - assert ok is False - assert any("font_size" in e for e in errors) - - def test_empty_font_color(self): - """空颜色.""" - ok, errors = validate_text_sticker( - { - "text": "Hi", - "font_color": "", - } - ) - assert ok is False - assert any("font_color" in e for e in errors) - - def test_negative_duration(self): - """负时长.""" - ok, errors = validate_text_sticker( - { - "text": "Hi", + "image_path": "a.png", "duration": -5, } ) - assert ok is False + assert valid is False assert any("duration" in e for e in errors) + + def test_invalid_start_time_negative(self): + valid, errors = validate_image_sticker( + { + "image_path": "a.png", + "start_time": -1, + } + ) + assert valid is False + assert any("start_time" in e for e in errors) + + def test_multiple_errors(self): + valid, errors = validate_image_sticker( + { + "opacity": 2.0, + "scale": -1, + "duration": -5, + } + ) + assert valid is False + assert len(errors) >= 3 + + def test_valid_with_extra_fields(self): + valid, _ = validate_image_sticker( + { + "image_path": "a.png", + "extra_field": "ignored", + "z_index": 5, + } + ) + assert valid is True + + +# ── validate_text_sticker ──────────────────────────────────── + + +class TestValidateTextSticker: + def test_valid_text(self): + valid, errors = validate_text_sticker({"text": "hello"}) + assert valid is True + assert errors == [] + + def test_missing_text(self): + valid, errors = validate_text_sticker({}) + assert valid is False + assert any("text" in e for e in errors) + + def test_empty_text(self): + valid, errors = validate_text_sticker({"text": ""}) + assert valid is False + assert any("text" in e for e in errors) + + def test_invalid_font_size_zero(self): + valid, errors = validate_text_sticker( + { + "text": "hello", + "font_size": 0, + } + ) + assert valid is False + assert any("font_size" in e for e in errors) + + def test_invalid_font_size_negative(self): + valid, errors = validate_text_sticker( + { + "text": "hello", + "font_size": -5, + } + ) + assert valid is False + + def test_missing_font_color(self): + valid, errors = validate_text_sticker( + { + "text": "hello", + "font_color": "", + } + ) + assert valid is False + assert any("font_color" in e for e in errors) + + def test_invalid_duration_negative(self): + valid, errors = validate_text_sticker( + { + "text": "hello", + "duration": -3, + } + ) + assert valid is False + assert any("duration" in e for e in errors) + + def test_default_font_size_valid(self): + # 默认36,有效 + valid, _ = validate_text_sticker({"text": "hi"}) + assert valid is True + + def test_multiple_errors(self): + valid, errors = validate_text_sticker( + { + "text": "", + "font_size": -1, + "font_color": "", + } + ) + assert valid is False + assert len(errors) >= 3