`api_key=volcengine.api_key` 这类**依赖注入传参**被 KEY-ASSIGN 判为疑似凭证。 这是规则的真缺口而非代码问题:行里没有任何秘密,而做 DI 的代码到处都是这种 写法——绕过一次就得在每个调用点绕过,那等于把规则废掉。故改规则。 新增 ALLOW_REFERENCE,刻意收得很紧以免开后门: - 值必须是**未加引号**的小写起首标识符引用(真密钥要么带引号,要么不是标识符形状) - 只允许**恰好一个点且随即行尾** - 连字符不在字符集内 对抗性夹具验证(三真三假): - 拦下 `api_key = "sk-T3Blbk…"`(OpenAI 形态) - 拦下 `secret_key: "AKID…"`(腾讯云形态) - 拦下 `auth_token=eyJ….eyJ….Sfl…`(**三段式 JWT——两个点,故不落进放行**) - 放行 `api_key=lowercase.reference` / `api_key = settings.api_key` / `api_token: config.authToken` 原 5 形态泄漏夹具复验仍 8 条命中,一条不少。 另更正口径:脚本头与 git-workflow.md 仍写「三仓同构」,实际已是四仓—— patbond-ai 是唯一持有 AI 服务商凭证的仓,漏同步它风险最大。四仓 md5 已一致 (4945940093b4b8413b7d3eec8bf6a5ec),四仓 --all 全绿。 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
"""`ArkClient` 的测试——只测传输层:鉴权头、错误解包、连接生命周期。
|
||||
|
||||
**刻意不测任何视频业务**:本 client 不认识「视频」,测试也不该。视频相关的断言
|
||||
在 `test_video.py`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.domain.generation import Retry, UserFacing
|
||||
from app.providers.volcengine.client import ArkClient, ArkError
|
||||
|
||||
#: 显式的假值。防泄漏扫描会拦下 `api_key = "..."` 形态(规则正确——这正是真实
|
||||
#: 密钥最常见的泄漏形态),故夹具用 ALLOW 清单认可的占位词。
|
||||
FAKE_API_KEY = "dummy-api-key-for-tests"
|
||||
|
||||
BASE_URL = "https://ark.example.invalid/api/v3"
|
||||
|
||||
|
||||
def client_with(handler) -> ArkClient:
|
||||
return ArkClient(
|
||||
api_key=FAKE_API_KEY,
|
||||
base_url=BASE_URL,
|
||||
client=httpx.Client(transport=httpx.MockTransport(handler)),
|
||||
)
|
||||
|
||||
|
||||
class TestConstruction:
|
||||
def test_missing_api_key_fails_at_construction_not_at_first_call(self):
|
||||
# 缺密钥是配置错误。让它表现为一串莫名的 401 会浪费排查时间。
|
||||
with pytest.raises(ValueError, match="ARK_API_KEY"):
|
||||
ArkClient(api_key="", base_url=BASE_URL)
|
||||
|
||||
def test_trailing_slash_in_base_url_does_not_double_up(self):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert "//contents" not in str(request.url)
|
||||
return httpx.Response(200, json={})
|
||||
|
||||
ArkClient(
|
||||
api_key=FAKE_API_KEY,
|
||||
base_url=BASE_URL + "/",
|
||||
client=httpx.Client(transport=httpx.MockTransport(handler)),
|
||||
).get("/contents/x")
|
||||
|
||||
|
||||
class TestAuthAndTransport:
|
||||
def test_bearer_token_and_content_type_are_sent(self):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.headers["Authorization"] == f"Bearer {FAKE_API_KEY}"
|
||||
assert request.headers["Content-Type"] == "application/json"
|
||||
return httpx.Response(200, json={"ok": True})
|
||||
|
||||
assert client_with(handler).post("/x", {}) == {"ok": True}
|
||||
|
||||
def test_get_and_post_hit_the_expected_method(self):
|
||||
seen: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen.append(request.method)
|
||||
return httpx.Response(200, json={})
|
||||
|
||||
client = client_with(handler)
|
||||
client.post("/x", {})
|
||||
client.get("/x")
|
||||
assert seen == ["POST", "GET"]
|
||||
|
||||
def test_network_failure_is_classified_retryable(self):
|
||||
def handler(request):
|
||||
raise httpx.ConnectError("connection refused")
|
||||
|
||||
with pytest.raises(ArkError) as exc:
|
||||
client_with(handler).get("/x")
|
||||
assert exc.value.failure.retry is Retry.BACKOFF
|
||||
assert exc.value.http_status is None
|
||||
|
||||
|
||||
class TestErrorUnwrapping:
|
||||
def test_vendor_error_body_is_classified(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
429,
|
||||
json={
|
||||
"error": {
|
||||
"code": "RateLimitExceeded.EndpointRPMExceeded",
|
||||
"message": "RPM limit exceeded",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(ArkError) as exc:
|
||||
client_with(handler).get("/x")
|
||||
assert exc.value.failure.retry is Retry.BACKOFF
|
||||
assert exc.value.failure.user_facing is UserFacing.RATE_LIMITED
|
||||
assert (
|
||||
exc.value.failure.provider_code == "RateLimitExceeded.EndpointRPMExceeded"
|
||||
)
|
||||
assert exc.value.http_status == 429
|
||||
|
||||
def test_vendor_message_is_preserved_for_troubleshooting(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
401,
|
||||
json={
|
||||
"error": {"code": "AuthenticationError", "message": "key invalid"}
|
||||
},
|
||||
)
|
||||
|
||||
with pytest.raises(ArkError) as exc:
|
||||
client_with(handler).get("/x")
|
||||
assert "key invalid" in exc.value.failure.message
|
||||
|
||||
def test_non_json_error_body_is_not_swallowed(self):
|
||||
# 打到错误地址时常见:网关返回 HTML 错误页。静默会让排查绕远路。
|
||||
def handler(request):
|
||||
return httpx.Response(502, text="<html>bad gateway</html>")
|
||||
|
||||
with pytest.raises(ArkError) as exc:
|
||||
client_with(handler).get("/x")
|
||||
assert "bad gateway" in exc.value.failure.message
|
||||
assert exc.value.failure.retry is Retry.BACKOFF
|
||||
|
||||
def test_non_json_success_body_is_an_error_too(self):
|
||||
def handler(request):
|
||||
return httpx.Response(200, text="not json")
|
||||
|
||||
with pytest.raises(ArkError, match="不是合法 JSON"):
|
||||
client_with(handler).get("/x")
|
||||
|
||||
|
||||
class TestConnectionOwnership:
|
||||
def test_injected_client_is_not_closed_by_us(self):
|
||||
"""注入进来的连接池归调用方管理。
|
||||
|
||||
在这里关掉会让共享同一个 httpx.Client 的其他适配器一起失效——接了第二个
|
||||
火山接口后这会变成一个极难查的偶发失败。
|
||||
"""
|
||||
injected = httpx.Client(
|
||||
transport=httpx.MockTransport(lambda r: httpx.Response(200, json={}))
|
||||
)
|
||||
ArkClient(api_key=FAKE_API_KEY, base_url=BASE_URL, client=injected).close()
|
||||
assert not injected.is_closed
|
||||
|
||||
def test_own_client_is_closed(self):
|
||||
client = ArkClient(api_key=FAKE_API_KEY, base_url=BASE_URL)
|
||||
client.close()
|
||||
assert client._client.is_closed
|
||||
|
||||
def test_usable_as_context_manager(self):
|
||||
with ArkClient(api_key=FAKE_API_KEY, base_url=BASE_URL) as client:
|
||||
inner = client._client
|
||||
assert inner.is_closed
|
||||
@@ -0,0 +1,176 @@
|
||||
"""火山方舟错误分类的测试。
|
||||
|
||||
每个用例对应官方错误码表里的一行或一类。重点在三处**如果搞错只会在生产暴露**
|
||||
的地方:`QuotaExceeded` 的一码两义、内容安全类必须不可重试、未知码必须偏向
|
||||
可重试而不是直接判死。
|
||||
"""
|
||||
|
||||
from app.domain.generation import Retry, UserFacing
|
||||
from app.providers.volcengine.errors import classify
|
||||
|
||||
|
||||
class TestQuotaExceededIsTwoDifferentThings:
|
||||
"""同一个 code,两种完全不同的处置。只看 code 必然错一半。"""
|
||||
|
||||
def test_queue_backlog_is_a_seconds_long_wait(self):
|
||||
# 官方原文:「当前账号处于排队中状态的任务数已超过限制,请稍后重试。」
|
||||
result = classify(
|
||||
"QuotaExceeded", "The request has exceeded the quota. Request ID: x."
|
||||
)
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.RATE_LIMITED
|
||||
|
||||
def test_queue_backlog_recognised_from_chinese_message(self):
|
||||
result = classify("QuotaExceeded", "当前账号处于排队中状态的任务数已超过限制")
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.RATE_LIMITED
|
||||
|
||||
def test_free_trial_exhausted_needs_billing_action(self):
|
||||
# 官方原文:「免费试用额度已消耗完毕,请前往控制台开通对应模型服务。」
|
||||
result = classify(
|
||||
"QuotaExceeded",
|
||||
"Your account [x] has exhausted its free trial quota for the [y] model.",
|
||||
)
|
||||
assert result.retry is Retry.QUOTA
|
||||
assert result.user_facing is UserFacing.QUOTA_EXHAUSTED
|
||||
|
||||
def test_periodic_limit_exhausted_needs_to_wait_for_reset(self):
|
||||
result = classify(
|
||||
"QuotaExceeded",
|
||||
"You have exceeded the 5-hour/weekly/monthly usage quota. It will reset at T.",
|
||||
)
|
||||
assert result.retry is Retry.QUOTA
|
||||
assert result.user_facing is UserFacing.QUOTA_EXHAUSTED
|
||||
|
||||
|
||||
class TestContentRejectionMustNotBeRetried:
|
||||
"""同样的输入必然同样被拒。重试只会白烧额度再失败。"""
|
||||
|
||||
def test_input_image_sensitive(self):
|
||||
result = classify("InputImageSensitiveContentDetected")
|
||||
assert result.retry is Retry.NEVER
|
||||
assert result.user_facing is UserFacing.CONTENT_REJECTED
|
||||
|
||||
def test_output_video_sensitive(self):
|
||||
result = classify("OutputVideoSensitiveContentDetected")
|
||||
assert result.retry is Retry.NEVER
|
||||
assert result.user_facing is UserFacing.CONTENT_REJECTED
|
||||
|
||||
def test_policy_violation_subcode(self):
|
||||
result = classify("InputVideoSensitiveContentDetected.PolicyViolation")
|
||||
assert result.retry is Retry.NEVER
|
||||
|
||||
def test_real_person_subcode(self):
|
||||
result = classify("InputImageSensitiveContentDetected.PrivacyInformation")
|
||||
assert result.retry is Retry.NEVER
|
||||
|
||||
def test_risk_detection_product_codes(self):
|
||||
assert classify("InputTextRiskDetection").retry is Retry.NEVER
|
||||
assert classify("OutputImageRiskDetection").retry is Retry.NEVER
|
||||
|
||||
def test_but_the_detector_itself_failing_is_retryable(self):
|
||||
# 风险识别产品请求失败 ≠ 内容真的违规。
|
||||
result = classify("ContentSecurityDetectionError", "Internal error.")
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.UPSTREAM_UNAVAILABLE
|
||||
|
||||
|
||||
class TestRateLimitFamily:
|
||||
def test_endpoint_rpm(self):
|
||||
result = classify("RateLimitExceeded.EndpointRPMExceeded")
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.RATE_LIMITED
|
||||
|
||||
def test_model_account_tpm(self):
|
||||
assert classify("ModelAccountTpmRateLimitExceeded").retry is Retry.BACKOFF
|
||||
|
||||
def test_server_overloaded(self):
|
||||
assert classify("ServerOverloaded").retry is Retry.BACKOFF
|
||||
|
||||
def test_request_burst_too_fast(self):
|
||||
# doubao-seed-2.0 之后版本的突增流量保护码。
|
||||
assert classify("RequestBurstTooFast").retry is Retry.BACKOFF
|
||||
|
||||
def test_images_per_minute(self):
|
||||
assert classify("ModelAccountIpmRateLimitExceeded").retry is Retry.BACKOFF
|
||||
|
||||
|
||||
class TestQuotaAndBillingFamily:
|
||||
def test_inference_limit_set_by_account(self):
|
||||
result = classify("SetLimitExceeded")
|
||||
assert result.retry is Retry.QUOTA
|
||||
assert result.user_facing is UserFacing.QUOTA_EXHAUSTED
|
||||
|
||||
def test_concurrency_cap_needs_topup(self):
|
||||
assert classify("InflightBatchsizeExceeded").retry is Retry.QUOTA
|
||||
|
||||
def test_account_overdue_is_403_but_same_user_action(self):
|
||||
# HTTP 状态码不同(403 而非 429),但用户要做的事一样:去充值。
|
||||
result = classify("AccountOverdueError")
|
||||
assert result.retry is Retry.QUOTA
|
||||
assert result.user_facing is UserFacing.QUOTA_EXHAUSTED
|
||||
|
||||
def test_model_not_activated(self):
|
||||
assert classify("ModelNotOpen").retry is Retry.QUOTA
|
||||
|
||||
|
||||
class TestOurOwnFaults:
|
||||
"""重试无意义,需要人改代码或改配置。"""
|
||||
|
||||
def test_bad_api_key(self):
|
||||
result = classify("AuthenticationError")
|
||||
assert result.retry is Retry.NEVER
|
||||
assert result.user_facing is UserFacing.SERVER_ERROR
|
||||
|
||||
def test_unknown_model_id(self):
|
||||
assert classify("InvalidEndpointOrModel.NotFound").retry is Retry.NEVER
|
||||
|
||||
def test_invalid_parameter(self):
|
||||
assert classify("InvalidParameter").retry is Retry.NEVER
|
||||
|
||||
def test_task_type_constraint_is_our_parameter_problem(self):
|
||||
# Seedance 2.5 全模态任务的参数与模型判定的任务类型不兼容。
|
||||
assert classify("InvalidParameter.TaskTypeConstraint").retry is Retry.NEVER
|
||||
|
||||
def test_task_type_mismatch(self):
|
||||
assert classify("InvalidParameter.TaskTypeMismatch").retry is Retry.NEVER
|
||||
|
||||
def test_missing_parameter(self):
|
||||
assert classify("MissingParameter").retry is Retry.NEVER
|
||||
|
||||
def test_payload_too_large(self):
|
||||
assert classify("RequestTooLarge").retry is Retry.NEVER
|
||||
|
||||
|
||||
class TestUpstreamErrors:
|
||||
def test_internal_service_error_is_retryable(self):
|
||||
result = classify("InternalServiceError")
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.UPSTREAM_UNAVAILABLE
|
||||
|
||||
|
||||
class TestUnknownCodesLeanTowardsRetry:
|
||||
"""厂商在持续新增错误码。把未知码判死会让一次抖动变成用户看到的失败;
|
||||
重试预算本身有上限,最坏只是多试两次。"""
|
||||
|
||||
def test_unknown_code(self):
|
||||
result = classify("SomeBrandNewCodeVolcengineAddedLastWeek")
|
||||
assert result.retry is Retry.BACKOFF
|
||||
assert result.user_facing is UserFacing.UPSTREAM_UNAVAILABLE
|
||||
|
||||
def test_missing_code(self):
|
||||
assert classify(None).retry is Retry.BACKOFF
|
||||
assert classify("").retry is Retry.BACKOFF
|
||||
|
||||
|
||||
class TestProviderCodeIsAlwaysPreserved:
|
||||
"""原始码绝不丢弃——排查时它是唯一线索。"""
|
||||
|
||||
def test_known_code(self):
|
||||
assert classify("ServerOverloaded").provider_code == "ServerOverloaded"
|
||||
|
||||
def test_unknown_code(self):
|
||||
assert classify("WeirdCode").provider_code == "WeirdCode"
|
||||
|
||||
def test_whitespace_is_trimmed(self):
|
||||
assert classify(" ServerOverloaded ").provider_code == "ServerOverloaded"
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Seedance 视频适配器的测试:领域请求 ↔ 厂商请求体的翻译,以及状态映射。
|
||||
|
||||
夹具里的响应体逐字取自官方文档的「返回格式」示例,避免测试通过而真实字段名对不上。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.domain.generation import (
|
||||
GenerationRequest,
|
||||
MediaKind,
|
||||
Retry,
|
||||
TaskState,
|
||||
UserFacing,
|
||||
)
|
||||
from app.providers.volcengine.client import ArkClient
|
||||
from app.providers.volcengine.models import SeedanceSubmission
|
||||
from app.providers.volcengine.video import PROVIDER_CODE, SeedanceVideoProvider
|
||||
|
||||
FAKE_API_KEY = "dummy-api-key-for-tests"
|
||||
|
||||
#: 官方查询文档「返回格式」一节的原样示例。
|
||||
OFFICIAL_SUCCESS_PAYLOAD = {
|
||||
"id": "cgt-2026****-****",
|
||||
"model": "doubao-seedance-2-0-260128",
|
||||
"status": "succeeded",
|
||||
"content": {
|
||||
"video_url": "https://ark-content-generation-cn-beijing.tos-cn-beijing.volces.com/xxx"
|
||||
},
|
||||
"usage": {"completion_tokens": 108900, "total_tokens": 108900},
|
||||
"created_at": 1779348818,
|
||||
"updated_at": 1779348874,
|
||||
"seed": 78674,
|
||||
"resolution": "720p",
|
||||
"ratio": "16:9",
|
||||
"duration": 5,
|
||||
"framespersecond": 24,
|
||||
"service_tier": "default",
|
||||
"execution_expires_after": 172800,
|
||||
"generate_audio": True,
|
||||
"draft": False,
|
||||
"priority": 0,
|
||||
}
|
||||
|
||||
|
||||
def provider_with(handler, **kwargs) -> SeedanceVideoProvider:
|
||||
client = ArkClient(
|
||||
api_key=FAKE_API_KEY,
|
||||
base_url="https://ark.example.invalid/api/v3",
|
||||
client=httpx.Client(transport=httpx.MockTransport(handler)),
|
||||
)
|
||||
return SeedanceVideoProvider(client, **kwargs)
|
||||
|
||||
|
||||
def video_request(**kwargs) -> GenerationRequest:
|
||||
defaults = dict(
|
||||
job_id="job-1",
|
||||
media_kind=MediaKind.VIDEO,
|
||||
model="doubao-seedance-x",
|
||||
prompt="一只猫",
|
||||
)
|
||||
return GenerationRequest(**{**defaults, **kwargs})
|
||||
|
||||
|
||||
class TestIdentity:
|
||||
def test_provider_code_matches_the_catalog_column(self):
|
||||
assert (
|
||||
provider_with(lambda r: httpx.Response(200, json={})).provider_code
|
||||
== PROVIDER_CODE
|
||||
)
|
||||
|
||||
def test_declares_itself_as_a_video_provider(self):
|
||||
assert (
|
||||
provider_with(lambda r: httpx.Response(200, json={})).media_kind
|
||||
is MediaKind.VIDEO
|
||||
)
|
||||
|
||||
|
||||
class TestSubmitTranslation:
|
||||
def test_text_to_video_sends_only_text(self):
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
import json
|
||||
|
||||
captured.update(json.loads(request.content))
|
||||
return httpx.Response(200, json={"id": "cgt-1"})
|
||||
|
||||
provider_with(handler).submit(video_request())
|
||||
assert captured["content"] == [{"type": "text", "text": "一只猫"}]
|
||||
|
||||
def test_input_url_becomes_first_frame_with_explicit_role(self):
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
import json
|
||||
|
||||
captured.update(json.loads(request.content))
|
||||
return httpx.Response(200, json={"id": "cgt-1"})
|
||||
|
||||
provider_with(handler).submit(video_request(input_url="https://x/a.png"))
|
||||
image = captured["content"][1]
|
||||
assert image["type"] == "image_url"
|
||||
assert image["image_url"]["url"] == "https://x/a.png"
|
||||
# role 省略时厂商按 first_frame 处理,但显式写出以免依赖默认行为。
|
||||
assert image["role"] == "first_frame"
|
||||
|
||||
def test_model_from_request_wins_over_the_configured_default(self):
|
||||
"""请求里的模型来自任务行冻结的快照,必须优先。
|
||||
|
||||
否则「任务记录里写的模型」与「实际调用的模型」会不一致,事后无法对账。
|
||||
"""
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
import json
|
||||
|
||||
captured.update(json.loads(request.content))
|
||||
return httpx.Response(200, json={"id": "cgt-1"})
|
||||
|
||||
provider_with(handler, default_model="fallback-model").submit(
|
||||
video_request(model="snapshot-model")
|
||||
)
|
||||
assert captured["model"] == "snapshot-model"
|
||||
|
||||
def test_configured_default_is_only_a_fallback(self):
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
import json
|
||||
|
||||
captured.update(json.loads(request.content))
|
||||
return httpx.Response(200, json={"id": "cgt-1"})
|
||||
|
||||
provider_with(handler, default_model="fallback-model").submit(
|
||||
video_request(model="")
|
||||
)
|
||||
assert captured["model"] == "fallback-model"
|
||||
|
||||
def test_no_model_anywhere_fails_before_calling_the_vendor(self):
|
||||
with pytest.raises(ValueError, match="未指定模型"):
|
||||
provider_with(lambda r: httpx.Response(200, json={})).submit(
|
||||
video_request(model="")
|
||||
)
|
||||
|
||||
def test_task_expiry_comes_from_config_not_the_vendor_default(self):
|
||||
# 厂商默认 48 小时,对交互式应用过长——被放弃的任务会在厂商侧挂两天。
|
||||
captured: dict = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
import json
|
||||
|
||||
captured.update(json.loads(request.content))
|
||||
return httpx.Response(200, json={"id": "cgt-1"})
|
||||
|
||||
provider_with(handler, task_expiry_sec=7200).submit(video_request())
|
||||
assert captured["execution_expires_after"] == 7200
|
||||
|
||||
def test_rejects_a_misrouted_image_request(self):
|
||||
with pytest.raises(ValueError, match="只处理视频生成"):
|
||||
provider_with(lambda r: httpx.Response(200, json={})).submit(
|
||||
video_request(media_kind=MediaKind.IMAGE)
|
||||
)
|
||||
|
||||
def test_returns_vendor_task_id(self):
|
||||
def handler(request):
|
||||
return httpx.Response(200, json={"id": "cgt-123"})
|
||||
|
||||
assert provider_with(handler).submit(video_request()) == "cgt-123"
|
||||
|
||||
def test_success_without_task_id_is_an_error(self):
|
||||
# 2xx 但没有 ID:我们再也查不到这个任务,而它可能已经在计费。
|
||||
def handler(request):
|
||||
return httpx.Response(200, json={"unexpected": True})
|
||||
|
||||
with pytest.raises(ValueError, match="缺少任务 ID"):
|
||||
provider_with(handler).submit(video_request())
|
||||
|
||||
|
||||
class TestSubmissionBody:
|
||||
"""`SeedanceSubmission` 自身的行为,不经过 HTTP。"""
|
||||
|
||||
def test_empty_content_is_rejected_locally(self):
|
||||
# 空内容必然被厂商拒,但那要花一次往返(还可能计入 RPM)。
|
||||
with pytest.raises(ValueError, match="至少要有一个"):
|
||||
SeedanceSubmission(model="m").to_body()
|
||||
|
||||
def test_last_frame_requested_by_default_for_a_free_cover_image(self):
|
||||
assert (
|
||||
SeedanceSubmission(model="m", prompt="x").to_body()["return_last_frame"]
|
||||
is True
|
||||
)
|
||||
|
||||
def test_optional_fields_are_omitted_when_unset(self):
|
||||
body = SeedanceSubmission(model="m", prompt="x").to_body()
|
||||
assert "safety_identifier" not in body
|
||||
assert "callback_url" not in body
|
||||
|
||||
|
||||
class TestFetchStateMapping:
|
||||
def test_succeeded(self):
|
||||
result = provider_with(
|
||||
lambda r: httpx.Response(200, json=OFFICIAL_SUCCESS_PAYLOAD)
|
||||
).fetch("cgt-1")
|
||||
assert result.state is TaskState.SUCCEEDED
|
||||
assert result.progress == 100
|
||||
assert result.asset_url.endswith("/xxx")
|
||||
assert result.ratio == "16:9"
|
||||
assert result.resolution == "720p"
|
||||
assert result.billing_tokens == 108900
|
||||
assert result.failure is None
|
||||
|
||||
def test_asset_url_carries_its_expiry_so_callers_cannot_treat_it_as_permanent(self):
|
||||
"""厂商 URL 只有 24 小时有效期,存成 external_url 会变死链。
|
||||
|
||||
把时效随 URL 一起给出,上层就没有理由把它当永久地址。
|
||||
"""
|
||||
result = provider_with(
|
||||
lambda r: httpx.Response(200, json=OFFICIAL_SUCCESS_PAYLOAD)
|
||||
).fetch("cgt-1")
|
||||
assert result.asset_url_expires_in_sec == 24 * 3600
|
||||
|
||||
def test_queued_maps_to_pending(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "queued", "content": {}}
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").state is TaskState.PENDING
|
||||
|
||||
def test_running_has_zero_progress_because_the_vendor_gives_none(self):
|
||||
# 不是缺陷:客户端契约本就不承诺平滑进度(ADR-023 §10)。
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "running", "content": {}}
|
||||
)
|
||||
|
||||
result = provider_with(handler).fetch("x")
|
||||
assert result.state is TaskState.RUNNING
|
||||
assert result.progress == 0
|
||||
|
||||
def test_cancelled_is_terminal_without_a_failure(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "cancelled", "content": {}}
|
||||
)
|
||||
|
||||
result = provider_with(handler).fetch("x")
|
||||
assert result.state is TaskState.CANCELLED
|
||||
assert result.state.is_terminal
|
||||
assert result.failure is None
|
||||
|
||||
def test_expired_maps_to_failed_and_stays_retryable(self):
|
||||
"""`expired` 只见于创建接口的回调说明,查询接口文档没列。
|
||||
|
||||
只按查询文档实现会让超时任务掉进未知分支。它是超时而非内容问题,故可重试;
|
||||
且厂商 expired 时不一定给 error.code,故单独分类而非走通用路径。
|
||||
"""
|
||||
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "expired", "content": {}}
|
||||
)
|
||||
|
||||
result = provider_with(handler).fetch("x")
|
||||
assert result.state is TaskState.FAILED
|
||||
assert result.failure.retry is Retry.BACKOFF
|
||||
assert result.failure.provider_code == "TaskExpired"
|
||||
|
||||
def test_unknown_status_keeps_the_task_alive(self):
|
||||
# 厂商新增状态时把在途任务判死更糟,最坏是等到我们自己的超时。
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "brand_new", "content": {}}
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").state is TaskState.RUNNING
|
||||
|
||||
def test_succeeded_without_a_url_is_treated_as_a_retryable_failure(self):
|
||||
"""厂商说成功却没给 URL——那不是成功。
|
||||
|
||||
放一个没有产物的「成功」给上层,只会把空指针推到更远的地方。
|
||||
"""
|
||||
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "succeeded", "content": {}}
|
||||
)
|
||||
|
||||
result = provider_with(handler).fetch("x")
|
||||
assert result.state is TaskState.FAILED
|
||||
assert result.failure.retry is Retry.BACKOFF
|
||||
assert result.failure.provider_code == "MissingVideoUrl"
|
||||
|
||||
|
||||
class TestFetchFailureClassification:
|
||||
def test_content_rejection_is_not_retried(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"id": "x",
|
||||
"status": "failed",
|
||||
"content": {},
|
||||
"error": {
|
||||
"code": "OutputVideoSensitiveContentDetected",
|
||||
"message": "output may contain sensitive information",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = provider_with(handler).fetch("x")
|
||||
assert result.failure.retry is Retry.NEVER
|
||||
assert result.failure.user_facing is UserFacing.CONTENT_REJECTED
|
||||
# 原始码与 message 都要带到上层——排查时它们是唯一线索。
|
||||
assert result.failure.provider_code == "OutputVideoSensitiveContentDetected"
|
||||
assert "sensitive" in result.failure.message
|
||||
|
||||
|
||||
class TestDurationPrecision:
|
||||
def test_frames_over_fps_is_exact(self):
|
||||
# 官方例子:133 帧 / 24fps = 5.54 秒。
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"id": "x",
|
||||
"status": "succeeded",
|
||||
"frames": 133,
|
||||
"framespersecond": 24,
|
||||
"content": {"video_url": "https://v"},
|
||||
},
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").duration_ms == 5542
|
||||
|
||||
def test_falls_back_to_the_vendors_floored_seconds(self):
|
||||
# duration 与 frames 只返回其一。只有 duration 时它是「帧数/24 向下取整」
|
||||
# 的约数,最多可能短 1 秒——可用,但不可当精确值。
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"id": "x",
|
||||
"status": "succeeded",
|
||||
"duration": 5,
|
||||
"content": {"video_url": "https://v"},
|
||||
},
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").duration_ms == 5000
|
||||
|
||||
def test_none_rather_than_a_made_up_zero(self):
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200, json={"id": "x", "status": "running", "content": {}}
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").duration_ms is None
|
||||
|
||||
|
||||
class TestCoverImage:
|
||||
def test_last_frame_becomes_the_cover_url(self):
|
||||
"""尾帧图可免费充当视频封面——iteration-4/03 R13 把缩略图列为视频成本项,
|
||||
实际上厂商白给。"""
|
||||
|
||||
def handler(request):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"id": "x",
|
||||
"status": "succeeded",
|
||||
"content": {
|
||||
"video_url": "https://v",
|
||||
"last_frame_url": "https://f.png",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert provider_with(handler).fetch("x").cover_url == "https://f.png"
|
||||
|
||||
|
||||
class TestPixelDimensionsAreLeftBlankOnPurpose:
|
||||
def test_no_invented_dimensions(self):
|
||||
"""火山只返回 ratio 与 resolution,不返回像素值。
|
||||
|
||||
换算需要一张随模型族变化的对照表;在 V7 目录种子定下模型族之前,
|
||||
留空比编一个可能错的尺寸好。
|
||||
"""
|
||||
result = provider_with(
|
||||
lambda r: httpx.Response(200, json=OFFICIAL_SUCCESS_PAYLOAD)
|
||||
).fetch("x")
|
||||
assert result.width_px is None
|
||||
assert result.height_px is None
|
||||
# 但原始信息要透出,供上层或后续实现换算。
|
||||
assert (result.ratio, result.resolution) == ("16:9", "720p")
|
||||
Reference in New Issue
Block a user