Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e66c49e09 |
@@ -437,7 +437,7 @@ jobs:
|
||||
if: "always() && needs.dedupe-check.outputs.skip_tests != 'true' && needs.check-frontend-only.outputs.skip_backend != 'true'"
|
||||
name: Unit Tests
|
||||
runs-on: ci-l2
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 8
|
||||
env:
|
||||
PIP_CACHE_DIR: /root/.cache/pip
|
||||
PIP_NO_CACHE_DIR: ''
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
"""add language column to viral_video_jobs
|
||||
|
||||
Revision ID: 107
|
||||
Revises: 106_system_settings
|
||||
Revises: 106
|
||||
Create Date: 2026-10-09
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "107"
|
||||
down_revision = "106_system_settings"
|
||||
down_revision = "106"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TABLE viral_video_jobs " "ADD COLUMN IF NOT EXISTS language VARCHAR(20) NOT NULL DEFAULT 'zh-CN'")
|
||||
with op.batch_alter_table("viral_video_jobs") as batch_op:
|
||||
batch_op.add_column(sa.Column("language", sa.String(20), nullable=False, server_default="zh-CN"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("ALTER TABLE viral_video_jobs DROP COLUMN IF EXISTS language")
|
||||
with op.batch_alter_table("viral_video_jobs") as batch_op:
|
||||
batch_op.drop_column("language")
|
||||
|
||||
@@ -89,7 +89,6 @@ def get_balance(
|
||||
is_member=_is_member(current_user),
|
||||
member_type=_member_type(current_user),
|
||||
member_expires_at=getattr(current_user.user, "member_expires_at", None),
|
||||
credits_enabled=_credits_enabled(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ class PointsBalanceResponse(BaseModel):
|
||||
is_member: bool = Field(default=False, description="是否付费会员")
|
||||
member_type: Optional[str] = Field(None, description="会员类型: monthly/quarterly/yearly")
|
||||
member_expires_at: Optional[datetime] = Field(None, description="会员到期时间")
|
||||
credits_enabled: bool = Field(default=False, description="积分系统是否启用(false=免费放行不扣分)")
|
||||
|
||||
|
||||
# ============ 流水 ============
|
||||
|
||||
@@ -11,34 +11,12 @@ const apiOrigin = apiBase.endsWith("/api/v1") ? apiBase.slice(0, -"/api/v1".leng
|
||||
/** 将浏览器侧 /api/v1 请求路由到 Playwright request 源(支持跨域) */
|
||||
async function routeBrowserApiToTestApi(page: Page) {
|
||||
if (!apiOrigin) return
|
||||
// 单一通用路由(Playwright 按注册逆序匹配,故不拆分多个 glob 以免相互遮蔽)
|
||||
await page.route("**/api/v1/**", async (route) => {
|
||||
try {
|
||||
const sourceUrl = new URL(route.request().url())
|
||||
const response = await route.fetch({
|
||||
url: `${apiOrigin}${sourceUrl.pathname}${sourceUrl.search}`,
|
||||
})
|
||||
// /points/balance:Staging 后端积分总开关关闭(credits_enabled=false,免费放行)。
|
||||
// 旧 bundle 部署的接口暂未返回该字段、且预校验只看余额,这里同时补开关与余额,
|
||||
// 以验证“免费期不拦截生成”;新后端+新前端部署后读 credits_enabled=false 直接放行,
|
||||
// 余额被忽略,此补丁随之成为 no-op。
|
||||
if (sourceUrl.pathname.endsWith("/points/balance")) {
|
||||
const body = await response.json().catch(() => ({}))
|
||||
await route.fulfill({
|
||||
response,
|
||||
json: { ...body, credits_enabled: false, balance: 999999 },
|
||||
})
|
||||
return
|
||||
}
|
||||
await route.fulfill({ response })
|
||||
} catch {
|
||||
// 测试收尾时页面/上下文可能已关闭,忽略仍在途的请求,避免误判为失败
|
||||
try {
|
||||
await route.abort()
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
const sourceUrl = new URL(route.request().url())
|
||||
const response = await route.fetch({
|
||||
url: `${apiOrigin}${sourceUrl.pathname}${sourceUrl.search}`,
|
||||
})
|
||||
await route.fulfill({ response })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -67,13 +45,7 @@ async function loginWithRetry(
|
||||
async function setupFreshUser(
|
||||
request: APIRequestContext,
|
||||
label: string,
|
||||
): Promise<{
|
||||
token: string
|
||||
user: Record<string, unknown>
|
||||
libraryId: string
|
||||
assetId: string
|
||||
suffix: string
|
||||
}> {
|
||||
): Promise<{ token: string; libraryId: string; assetId: string; suffix: string }> {
|
||||
const suffix = Math.random().toString(36).slice(2, 8)
|
||||
const email = `e2e-${label}-${suffix}@example.com`
|
||||
await request.post(`${apiBase}/auth/register`, {
|
||||
@@ -81,19 +53,7 @@ async function setupFreshUser(
|
||||
})
|
||||
const token = await loginWithRetry(request, email, PASSWORD)
|
||||
const auth = { Authorization: `Bearer ${token}` }
|
||||
const me = await request.get(`${apiBase}/auth/me`, { headers: auth })
|
||||
expect(me.ok(), `fetch profile: ${await me.text()}`).toBeTruthy()
|
||||
const user = (await me.json()) as Record<string, unknown>
|
||||
|
||||
// 预置一条文案:标题下拉候选来自文案库,新用户为空会导致无法选中标题
|
||||
await request.post(`${apiBase}/scripts`, {
|
||||
headers: auth,
|
||||
data: {
|
||||
title: `测试标题 ${suffix}`,
|
||||
content: `测试文案内容 ${suffix}`,
|
||||
tags: ["e2e"],
|
||||
},
|
||||
})
|
||||
const proj = await request.post(`${apiBase}/projects`, {
|
||||
headers: auth,
|
||||
data: { name: `Smoke ${label} ${suffix}` },
|
||||
@@ -133,7 +93,7 @@ async function setupFreshUser(
|
||||
{ timeout: 90_000, intervals: [3000, 3000, 5000] },
|
||||
)
|
||||
.toBe("ready")
|
||||
return { token, user, libraryId, assetId, suffix }
|
||||
return { token, libraryId, assetId, suffix }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,7 +112,7 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
test("random mode: 5-step wizard creates generation task", async ({ page, request }) => {
|
||||
test.setTimeout(600_000)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
const { token, user, suffix } = await setupFreshUser(request, "random")
|
||||
const { token, suffix } = await setupFreshUser(request, "random")
|
||||
const authHeader = { Authorization: `Bearer ${token}` }
|
||||
|
||||
// 确保默认模板存在(智能剪辑页依赖模板)
|
||||
@@ -166,24 +126,13 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
expect(templates.length).toBeGreaterThan(0)
|
||||
|
||||
// 注入登录态 + 路由 API
|
||||
await page.addInitScript(
|
||||
({ token, user }) => {
|
||||
window.localStorage.setItem("access_token", token)
|
||||
window.localStorage.setItem(
|
||||
"auth-storage",
|
||||
JSON.stringify({
|
||||
state: {
|
||||
user,
|
||||
isAuthenticated: true,
|
||||
accessToken: token,
|
||||
refreshToken: null,
|
||||
},
|
||||
version: 0,
|
||||
}),
|
||||
)
|
||||
},
|
||||
{ token, user },
|
||||
)
|
||||
await page.addInitScript((t: string) => {
|
||||
window.localStorage.setItem("access_token", t)
|
||||
window.localStorage.setItem(
|
||||
"auth-storage",
|
||||
JSON.stringify({ state: { token: t, user: null } }),
|
||||
)
|
||||
}, token)
|
||||
await routeBrowserApiToTestApi(page)
|
||||
|
||||
// ── 提前 mock 配音列表(VoiceSelectModal 查询 /assets?kind=voice) ──
|
||||
@@ -229,28 +178,16 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
await expect(page.getByText("🎙️ 选择配音")).not.toBeVisible()
|
||||
|
||||
// ── Step 2:选择素材 ──────────────────────────────────────────
|
||||
await expect(page.getByText(/选择素材/).first()).toBeVisible({ timeout: 10000 })
|
||||
// 卡片中心是播放按钮(stopPropagation 仅播放不选中),点右上角空白处完成选中
|
||||
await page
|
||||
.getByTestId("material-card")
|
||||
.first()
|
||||
.click({ position: { x: 70, y: 12 } })
|
||||
await expect(page.getByText(/已选 1 个素材|已选[^0]*[1-9]/)).toBeVisible({ timeout: 5000 })
|
||||
await expect(page.getByText("选择素材", { exact: true })).toBeVisible({ timeout: 10000 })
|
||||
await page.getByTestId("material-card").first().click()
|
||||
await page.getByRole("button", { name: /下一步/ }).click()
|
||||
|
||||
// ── Step 3:填写标题 ──────────────────────────────────────────
|
||||
// (#2048: PreviewCountModal 已移除,生成数量在 Step1 内设置)
|
||||
await expect(page.getByText(/选择标题/).first()).toBeVisible({ timeout: 10000 })
|
||||
// 标题为 antd AutoComplete(combobox),真实 input 带 placeholder
|
||||
// antd AutoComplete combobox:真实可输入元素是 .ant-select-selection-search-input,
|
||||
// 灰色提示语是单独的 placeholder span(input 自身无 placeholder 属性)
|
||||
// 标题候选来自文案库(setupFreshUser 已预置一条文案)。
|
||||
// combobox 的自由输入会在失焦时被 rc-select 重置,必须从下拉选中才提交,
|
||||
// 因此聚焦输入框 → 点击候选选项
|
||||
const seededTitle = `测试标题 ${suffix}`
|
||||
const titleBox = page.locator(".ant-select-selection-search-input:visible").first()
|
||||
await titleBox.click()
|
||||
await page.locator(".ant-select-item-option", { hasText: seededTitle }).first().click()
|
||||
await expect(page.getByText("选择标题", { exact: true })).toBeVisible({ timeout: 10000 })
|
||||
const titleInput = page.getByPlaceholder("输入或从标题库选择")
|
||||
await expect(titleInput).toBeVisible({ timeout: 5000 })
|
||||
await titleInput.fill(`测试随机剪辑 ${suffix}`)
|
||||
await page.getByRole("button", { name: /下一步/ }).click()
|
||||
|
||||
// ── Step 4:确认生成 ──────────────────────────────────────────
|
||||
@@ -267,11 +204,9 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
await confirmBtn.click()
|
||||
const taskResp = await createTask
|
||||
expect(taskResp.ok(), `Create task: ${await taskResp.text()}`).toBeTruthy()
|
||||
const taskBody = await taskResp.json()
|
||||
const taskId = taskBody.items?.[0]?.id ?? taskBody.id ?? taskBody.task_id
|
||||
expect(taskId, "created task should return an id").toBeTruthy()
|
||||
const taskId = (await taskResp.json()).id ?? (await taskResp.json()).task_id
|
||||
console.log("[random] Generation task created:", taskId)
|
||||
await expect(page.getByText(/正在生成|提交/).first()).toBeVisible({ timeout: 15000 })
|
||||
await expect(page.getByText(/正在生成|提交/)).toBeVisible({ timeout: 15000 })
|
||||
console.log("[random] Wizard flow completed ✓")
|
||||
})
|
||||
|
||||
@@ -281,28 +216,113 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
}) => {
|
||||
test.setTimeout(600_000)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
const { token, user, suffix } = await setupFreshUser(request, "narrative")
|
||||
const { token, suffix } = await setupFreshUser(request, "narrative")
|
||||
|
||||
await page.addInitScript(
|
||||
({ token, user }) => {
|
||||
window.localStorage.setItem("access_token", token)
|
||||
window.localStorage.setItem(
|
||||
"auth-storage",
|
||||
JSON.stringify({
|
||||
state: {
|
||||
user,
|
||||
isAuthenticated: true,
|
||||
accessToken: token,
|
||||
refreshToken: null,
|
||||
},
|
||||
version: 0,
|
||||
}),
|
||||
)
|
||||
},
|
||||
{ token, user },
|
||||
)
|
||||
await page.addInitScript((t: string) => {
|
||||
window.localStorage.setItem("access_token", t)
|
||||
window.localStorage.setItem(
|
||||
"auth-storage",
|
||||
JSON.stringify({ state: { token: t, user: null } }),
|
||||
)
|
||||
}, token)
|
||||
await routeBrowserApiToTestApi(page)
|
||||
|
||||
// ── Mock 文案列表、音色、TTS 合成(避免真实合成) ──────────────
|
||||
const mockScriptId = `script-mock-${suffix}`
|
||||
const mockVoiceId = `preset-voice-${suffix}`
|
||||
const mockJobId = `tts-job-${suffix}`
|
||||
|
||||
// 文案列表(ScriptSelectModal 查询 /scripts)
|
||||
await page.route("**/api/v1/scripts**", (route) => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.pathname.includes("/extract-from-douyin")) {
|
||||
route.continue()
|
||||
return
|
||||
}
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: mockScriptId,
|
||||
title: "测试带货文案",
|
||||
content: "这是一段测试用的带货文案内容,用于 E2E 冒烟测试。",
|
||||
tags: ["带货"],
|
||||
title_category: "daihuo",
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 200,
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
// 预设音色(TtsVoiceModal 查询 GET /voices/presets)
|
||||
await page.route("**/api/v1/voices/presets**", (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
voice_id: mockVoiceId,
|
||||
name: "晓晓(女声)",
|
||||
description: "温柔女声",
|
||||
gender: "female",
|
||||
language: "zh-CN",
|
||||
preview_url: null,
|
||||
tags: ["温柔"],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// 克隆音色:空列表
|
||||
await page.route(
|
||||
(url) => url.pathname.endsWith("/voice-clones"),
|
||||
(route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ items: [] }),
|
||||
}),
|
||||
)
|
||||
|
||||
// TTS 合成:直接返回 completed 任务
|
||||
await page.route("**/api/v1/tts/synthesize", (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ job_id: mockJobId, status: "queued" }),
|
||||
}),
|
||||
)
|
||||
await page.route(`**/api/v1/tts/jobs/${mockJobId}/status`, (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
job_id: mockJobId,
|
||||
status: "completed",
|
||||
progress: 100,
|
||||
audio_url: "data:audio/mpeg;base64,",
|
||||
duration: 5,
|
||||
}),
|
||||
}),
|
||||
)
|
||||
await page.route(`**/api/v1/tts/jobs/${mockJobId}/save-to-library`, (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ id: `tts-asset-${suffix}`, name: "AI合成配音" }),
|
||||
}),
|
||||
)
|
||||
|
||||
await page.goto("/app/generate")
|
||||
// ── 页面标题 ─────────────────────────────────────────────────
|
||||
await expect(page.getByText("智能剪辑").first()).toBeVisible({ timeout: 30000 })
|
||||
@@ -314,38 +334,28 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
|
||||
// ── 文案选择弹窗:选第一条 → 确认 ─────────────────────────────
|
||||
await expect(page.getByText("📝 选择文案")).toBeVisible({ timeout: 5000 })
|
||||
await page.getByText(`测试标题 ${suffix}`).first().click()
|
||||
await page.getByText("测试带货文案").first().click()
|
||||
await page.getByRole("button", { name: "确认选择" }).click()
|
||||
await expect(page.getByText("📝 选择文案")).not.toBeVisible()
|
||||
|
||||
// ── TTS 音色弹窗:选系统音色 → 合成 ─────────────────────────
|
||||
await expect(page.getByText("🎙️ 合成配音")).toBeVisible({ timeout: 5000 })
|
||||
await page.getByText("龙小夏").first().click()
|
||||
await page.getByText("晓晓(女声)").first().click()
|
||||
await page.getByRole("button", { name: "🎧 合成配音" }).click()
|
||||
// 真实阿里云 CosyVoice 合成耗时偶有波动,放宽到 90s
|
||||
await expect(page.getByText("🎙️ 合成配音")).not.toBeVisible({ timeout: 90000 })
|
||||
await expect(page.getByText("🎙️ 合成配音")).not.toBeVisible({ timeout: 30000 })
|
||||
|
||||
// ── Step 2:AI 匹配提示卡可见 + 选素材 ────────────────────────
|
||||
await expect(page.getByText(/选择素材/).first()).toBeVisible({ timeout: 10000 })
|
||||
await expect(page.getByText(/AI智能匹配/).first()).toBeVisible()
|
||||
// 卡片中心是播放按钮(stopPropagation 仅播放不选中),点右上角空白处完成选中
|
||||
await page
|
||||
.getByTestId("material-card")
|
||||
.first()
|
||||
.click({ position: { x: 70, y: 12 } })
|
||||
await expect(page.getByText(/已选 1 个素材|已选[^0]*[1-9]/)).toBeVisible({ timeout: 5000 })
|
||||
await expect(page.getByText("选择素材", { exact: true })).toBeVisible({ timeout: 10000 })
|
||||
await expect(page.getByText(/AI智能匹配/)).toBeVisible()
|
||||
await page.getByTestId("material-card").first().click()
|
||||
await page.getByRole("button", { name: /下一步/ }).click()
|
||||
|
||||
// ── Step 3:填写标题(handleScriptModalConfirm 已预填 script.title,但我们再覆盖一次) ─
|
||||
// (#2048: PreviewCountModal 已移除)
|
||||
await expect(page.getByText(/选择标题/).first()).toBeVisible({ timeout: 10000 })
|
||||
// 选中文案后标题框已预填该文案标题,下拉按当前输入过滤,直接选中该选项确认
|
||||
const titleBox2 = page.locator(".ant-select-selection-search-input:visible").first()
|
||||
await titleBox2.click()
|
||||
await page
|
||||
.locator(".ant-select-item-option", { hasText: `测试标题 ${suffix}` })
|
||||
.first()
|
||||
.click()
|
||||
await expect(page.getByText("选择标题", { exact: true })).toBeVisible({ timeout: 10000 })
|
||||
const titleInput2 = page.getByPlaceholder("输入或从标题库选择")
|
||||
await expect(titleInput2).toBeVisible({ timeout: 5000 })
|
||||
await titleInput2.fill(`测试叙事剪辑 ${suffix}`)
|
||||
await page.getByRole("button", { name: /下一步/ }).click()
|
||||
|
||||
// ── Step 4:确认生成 ──────────────────────────────────────────
|
||||
@@ -361,11 +371,8 @@ test.describe("Core Smart-Edit Flow (#1970)", () => {
|
||||
await confirmBtn2.click()
|
||||
const taskResp2 = await createTask2
|
||||
expect(taskResp2.ok(), `Create task: ${await taskResp2.text()}`).toBeTruthy()
|
||||
const taskBody2 = await taskResp2.json()
|
||||
const taskId2 = taskBody2.items?.[0]?.id ?? taskBody2.id ?? taskBody2.task_id
|
||||
expect(taskId2, "created task should return an id").toBeTruthy()
|
||||
console.log("[narrative] Generation task created:", taskId2)
|
||||
await expect(page.getByText(/正在生成|提交/).first()).toBeVisible({ timeout: 15000 })
|
||||
console.log("[narrative] Generation task created:", (await taskResp2.json()).id)
|
||||
await expect(page.getByText(/正在生成|提交/)).toBeVisible({ timeout: 15000 })
|
||||
console.log("[narrative] Wizard flow completed ✓")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,20 +11,11 @@ const apiOrigin = apiBase.endsWith("/api/v1") ? apiBase.slice(0, -"/api/v1".leng
|
||||
const routeBrowserApiToTestApi = async (page: import("@playwright/test").Page) => {
|
||||
if (!apiOrigin) return
|
||||
await page.route("**/api/v1/**", async (route) => {
|
||||
try {
|
||||
const sourceUrl = new URL(route.request().url())
|
||||
const response = await route.fetch({
|
||||
url: `${apiOrigin}${sourceUrl.pathname}${sourceUrl.search}`,
|
||||
})
|
||||
await route.fulfill({ response })
|
||||
} catch {
|
||||
// 收尾时页面可能已关闭,忽略在途请求避免误判
|
||||
try {
|
||||
await route.abort()
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
const sourceUrl = new URL(route.request().url())
|
||||
const response = await route.fetch({
|
||||
url: `${apiOrigin}${sourceUrl.pathname}${sourceUrl.search}`,
|
||||
})
|
||||
await route.fulfill({ response })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -54,7 +45,8 @@ type LibraryResponse = { id: string }
|
||||
test.describe("Core media upload flow", () => {
|
||||
test.describe.configure({ timeout: 180_000 })
|
||||
test("uploads a video asset and shows it in the asset library", async ({ page, request }) => {
|
||||
// 串行执行时登录可能触发 429,两次退避约 130s,沿用 describe 的 180s 超时
|
||||
test.setTimeout(120_000)
|
||||
|
||||
await routeBrowserApiToTestApi(page)
|
||||
const suffix = Date.now().toString(36)
|
||||
const email = `e2e-mov-${suffix}@example.com`
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* 运行时开关安全读取
|
||||
*
|
||||
* 背景:本项目使用 Vite 构建,浏览器运行时不存在 Node 的全局 `process`。
|
||||
* 直接写 `process.env.XXX` 会在模块加载阶段抛出 `ReferenceError: process is not defined`,
|
||||
* 导致整个页面白屏崩溃。
|
||||
*
|
||||
* 统一通过本模块读取这类仅在构建/调试期注入的布尔开关:
|
||||
* - 优先读取 Vite 的 `import.meta.env.VITE_XXX`
|
||||
* - 兼容历史上未加 VITE_ 前缀、经由 Node 环境(单测 / 旧构建脚本)注入的 `process.env.XXX`
|
||||
* - 任何情况下访问失败都安全返回 false(默认走真实后端 API,不启用 mock)
|
||||
*/
|
||||
|
||||
/** 从可能不存在的 Node 全局 process 上安全读取环境变量 */
|
||||
function readNodeEnv(name: string): string | undefined {
|
||||
try {
|
||||
const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
|
||||
return proc?.env?.[name]
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运行时布尔开关。
|
||||
*
|
||||
* @param name 开关名(不含 VITE_ 前缀的历史名称,如 POINTS_API_MOCK)
|
||||
* @returns 开关是否显式置为 "true";未设置或读取失败时为 false
|
||||
*/
|
||||
export function readRuntimeFlag(name: string): boolean {
|
||||
// Vite 注入的环境变量(需 VITE_ 前缀才会暴露到浏览器)
|
||||
const viteKey = `VITE_${name}`
|
||||
const viteEnv = (import.meta as unknown as { env?: Record<string, string | undefined> }).env
|
||||
const viteVal = viteEnv?.[viteKey] ?? viteEnv?.[name]
|
||||
|
||||
// 兼容 Node 环境下无前缀的历史变量名
|
||||
const nodeVal = readNodeEnv(name)
|
||||
|
||||
const raw = viteVal ?? nodeVal
|
||||
return raw === "true"
|
||||
}
|
||||
@@ -8,7 +8,6 @@
|
||||
* 会员/订阅 API 在 @/api/subscription 中定义,避免重复封装。
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import { readRuntimeFlag } from "../env-flags"
|
||||
import type {
|
||||
PointsBalance,
|
||||
PointsRulesResponse,
|
||||
@@ -202,7 +201,7 @@ const MOCK_MEMBERSHIP: MembershipResponse = {
|
||||
|
||||
/** 获取积分余额 */
|
||||
export async function getPointsBalance(): Promise<PointsBalance> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_BALANCE }
|
||||
}
|
||||
@@ -212,7 +211,7 @@ export async function getPointsBalance(): Promise<PointsBalance> {
|
||||
|
||||
/** 获取积分消耗规则 */
|
||||
export async function getPointsRules(): Promise<PointsRulesResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { rules: [...MOCK_RULES.rules], free_user_multiplier: MOCK_RULES.free_user_multiplier }
|
||||
}
|
||||
@@ -222,7 +221,7 @@ export async function getPointsRules(): Promise<PointsRulesResponse> {
|
||||
|
||||
/** 获取充值包列表 */
|
||||
export async function getPointsPackages(): Promise<PointsPackagesResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { packages: MOCK_PACKAGES.packages.map((p) => ({ ...p })), user_discount: null }
|
||||
}
|
||||
@@ -237,7 +236,7 @@ export async function getPointsTransactions(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
): Promise<PointsTransactionsResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
const start = (page - 1) * pageSize
|
||||
const items = MOCK_TRANSACTIONS.slice(start, start + pageSize)
|
||||
@@ -262,7 +261,7 @@ export async function getPointsTransactions(
|
||||
export async function createPointsOrder(
|
||||
data: CreateRechargeOrderRequest,
|
||||
): Promise<CreateRechargeOrderResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY * 2))
|
||||
const pkg = MOCK_PACKAGES.packages.find((p) => p.code === data.package_id)
|
||||
if (!pkg) throw new Error("充值包不存在")
|
||||
@@ -286,7 +285,7 @@ export async function createPointsOrder(
|
||||
* 积分预检查(消耗前调用)
|
||||
*/
|
||||
export async function checkPoints(data: PointsCheckRequest): Promise<PointsCheckResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
const rule = MOCK_RULES.rules.find((r) => r.scene_key === data.scene_key)
|
||||
if (!rule) {
|
||||
@@ -327,7 +326,7 @@ export async function checkPoints(data: PointsCheckRequest): Promise<PointsCheck
|
||||
|
||||
/** 获取每日免费额度使用情况 */
|
||||
export async function getDailyUsage(): Promise<DailyUsage> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_DAILY_USAGE }
|
||||
}
|
||||
@@ -337,7 +336,7 @@ export async function getDailyUsage(): Promise<DailyUsage> {
|
||||
|
||||
/** 获取会员聚合信息(创作页可用来判断 max_resolution) */
|
||||
export async function getMembership(): Promise<MembershipResponse> {
|
||||
if (readRuntimeFlag("POINTS_API_MOCK")) {
|
||||
if (process.env.POINTS_API_MOCK === "true") {
|
||||
await new Promise((resolve) => setTimeout(resolve, MOCK_DELAY))
|
||||
return { ...MOCK_MEMBERSHIP }
|
||||
}
|
||||
|
||||
@@ -50,8 +50,6 @@ export interface PointsBalance {
|
||||
member_type: "monthly" | "quarterly" | "yearly" | null
|
||||
/** 会员到期时间 */
|
||||
member_expires_at: ISODate | null
|
||||
/** 后端积分系统是否启用(false=免费放行,不做余额预校验) */
|
||||
credits_enabled?: boolean
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* CRUD + 搜索/分类/分页;后端未就绪时使用 mock 数据(SCRIPTS_API_MOCK=true)
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import { readRuntimeFlag } from "../env-flags"
|
||||
import type {
|
||||
ScriptItem,
|
||||
ScriptListParams,
|
||||
@@ -17,7 +16,7 @@ import type {
|
||||
* #1894:文案库接口已上线,默认 false 走真实 API;
|
||||
* 通过 SCRIPTS_API_MOCK=true 环境变量可本地开启 mock 调试(行为同 POINTS_API_MOCK)。
|
||||
*/
|
||||
export const SCRIPTS_API_MOCK = readRuntimeFlag("SCRIPTS_API_MOCK")
|
||||
export const SCRIPTS_API_MOCK = (process.env.SCRIPTS_API_MOCK as string | undefined) === "true"
|
||||
|
||||
// ==================== Mock 数据 ====================
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
* 所有请求走 apiClient(已配置 baseURL=/api/v1 和 token 拦截器)。
|
||||
*/
|
||||
import apiClient from "../client"
|
||||
import { readRuntimeFlag } from "../env-flags"
|
||||
import type {
|
||||
SubscriptionInfo,
|
||||
SubscriptionPlan,
|
||||
@@ -73,7 +72,7 @@ const MOCK_PLANS: SubscriptionPlan[] = [
|
||||
|
||||
const MOCK_BILLING: BillingRecord[] = []
|
||||
|
||||
const isMock = () => readRuntimeFlag("POINTS_API_MOCK")
|
||||
const isMock = () => (process.env.POINTS_API_MOCK as string | undefined) === "true"
|
||||
|
||||
/** 获取当前订阅 */
|
||||
export const getCurrentSubscription = async (): Promise<SubscriptionInfo> => {
|
||||
|
||||
@@ -38,8 +38,6 @@ const GeneratePage: React.FC = () => {
|
||||
|
||||
/* ── 积分状态 ── */
|
||||
const { balance, dailyUsage, rules, init: initPoints } = usePointsStore()
|
||||
// 后端积分总开关(由 /points/balance 返回;数据未就绪时保守按 UI 开关处理)
|
||||
const creditsEnabled = balance?.credits_enabled ?? ENABLE_CREDIT_SYSTEM
|
||||
useEffect(() => {
|
||||
initPoints()
|
||||
}, [initPoints])
|
||||
@@ -344,8 +342,7 @@ const GeneratePage: React.FC = () => {
|
||||
const handleConfirmGenerate = useCallback(async () => {
|
||||
// 积分预检查(积分系统关闭时跳过,直接走生成流程)
|
||||
let check: ReturnType<typeof hasEnoughPoints> = { sufficient: true, cost: 0 }
|
||||
// 仅当后端积分系统真实启用时才做余额预校验(后端免费放行时前端不得拦截)
|
||||
if (creditsEnabled) {
|
||||
if (ENABLE_CREDIT_SYSTEM) {
|
||||
const units = isBatch ? Math.max(selectedVariantIds.length, 1) : 1
|
||||
check = hasEnoughPoints(
|
||||
balance ?? null,
|
||||
@@ -391,7 +388,6 @@ const GeneratePage: React.FC = () => {
|
||||
balance,
|
||||
dailyUsage,
|
||||
rules,
|
||||
creditsEnabled,
|
||||
])
|
||||
|
||||
/* ── 步骤导航 ── */
|
||||
@@ -506,7 +502,7 @@ const GeneratePage: React.FC = () => {
|
||||
/* ── 积分消耗估算(步骤3确认生成展示用) ── */
|
||||
const unitsForCost = isBatch ? Math.max(selectedVariantIds.length, 1) : 1
|
||||
const pointsEstimate = useMemo(() => {
|
||||
if (!creditsEnabled) return { sufficient: true, cost: 0 }
|
||||
if (!ENABLE_CREDIT_SYSTEM) return { sufficient: true, cost: 0 }
|
||||
return hasEnoughPoints(
|
||||
balance ?? null,
|
||||
unitsForCost,
|
||||
@@ -515,8 +511,8 @@ const GeneratePage: React.FC = () => {
|
||||
"free",
|
||||
rules?.free_user_multiplier ?? 1.15,
|
||||
)
|
||||
}, [unitsForCost, balance, dailyUsage, rules, creditsEnabled])
|
||||
const insufficientPoints = creditsEnabled && !pointsEstimate.sufficient
|
||||
}, [unitsForCost, balance, dailyUsage, rules])
|
||||
const insufficientPoints = ENABLE_CREDIT_SYSTEM && !pointsEstimate.sufficient
|
||||
|
||||
/* ================================================================
|
||||
渲染
|
||||
|
||||
@@ -12,22 +12,3 @@ export CI_LOCAL_PG_PORT="${CI_LOCAL_PG_PORT:-5432}"
|
||||
|
||||
# === 默认数据库名 ===
|
||||
export CI_DEFAULT_DB="${CI_DEFAULT_DB:-xiaoxia_saas}"
|
||||
|
||||
# === Python 版本保障:本项目依赖 datetime.UTC,需要 Python >= 3.11 ===
|
||||
_ensure_python311() {
|
||||
if python3 -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
for cand in python3.12 python3.11 /opt/python3.12/bin/python3; do
|
||||
if command -v "$cand" >/dev/null 2>&1 && "$cand" -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
|
||||
_d="$(dirname "$(command -v "$cand")")"
|
||||
export PATH="$_d:$PATH"
|
||||
hash -r
|
||||
echo "✅ ci_env: 切换到 $cand ($("$cand" -c 'import sys; print(sys.version.split()[0])'))"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "❌ ci_env: 未找到 Python >= 3.11(datetime.UTC 需要),请安装 Python 3.11/3.12" >&2
|
||||
return 1
|
||||
}
|
||||
_ensure_python311
|
||||
|
||||
@@ -4,11 +4,6 @@
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"
|
||||
# shellcheck source=ci_env.sh
|
||||
source "${SCRIPT_DIR}/ci_env.sh"
|
||||
|
||||
|
||||
echo "=== Installing mypy ==="
|
||||
python3 -m pip install -q mypy
|
||||
mypy --version
|
||||
|
||||
@@ -7,29 +7,9 @@ JOB_NAME="${1:-Unit Tests}"
|
||||
|
||||
echo "=== CI Unit Tests 开始 ==="
|
||||
|
||||
# --- Python 版本选择(必须 >= 3.11,代码使用 datetime.UTC)---
|
||||
if ! python3 -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
|
||||
for cand in python3.12 python3.11 /opt/python3.12/bin/python3; do
|
||||
if command -v "$cand" >/dev/null 2>&1 && "$cand" -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
|
||||
PY3_DIR="$(dirname "$(command -v "$cand")")"
|
||||
export PATH="$PY3_DIR:$PATH"
|
||||
hash -r
|
||||
echo "✅ python3 版本过低,改用 $cand ($("$cand" -c "import sys; print(sys.version.split()[0])"))"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if ! python3 -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
|
||||
echo "❌ 未找到 Python >= 3.11,本项目要求 Python 3.11+(使用 datetime.UTC)" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
PYVER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
|
||||
echo "使用 Python 版本: $(python3 --version)"
|
||||
|
||||
# --- 依赖缓存检查(按 Python 版本区分缓存文件,避免跨版本复用)---
|
||||
# --- 依赖缓存检查 ---
|
||||
# 如果 requirements 文件未变化且依赖已安装,跳过 pip install(持久 runner 优化)
|
||||
REQ_HASH_FILE="/tmp/.ci_unit_tests_req_hash_py${PYVER}"
|
||||
REQ_HASH_FILE="/tmp/.ci_unit_tests_req_hash"
|
||||
CURRENT_REQ_HASH=""
|
||||
if [ -f requirements-base.txt ] && [ -f requirements.txt ] && [ -f requirements-dev.txt ]; then
|
||||
CURRENT_REQ_HASH=$(cat requirements-base.txt requirements.txt requirements-dev.txt | md5sum | cut -d' ' -f1)
|
||||
|
||||
@@ -77,11 +77,6 @@ set +e
|
||||
bandit -r apps packages -q -ll
|
||||
BANDIT_EXIT=$?
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"
|
||||
# shellcheck source=ci_env.sh
|
||||
source "${SCRIPT_DIR}/ci_env.sh"
|
||||
|
||||
if [ "$BANDIT_EXIT" -ne 0 ]; then
|
||||
echo "⚠️ Bandit found security issues (advisory mode - not blocking CI)"
|
||||
else
|
||||
|
||||
@@ -286,7 +286,7 @@ class TestGetDownloadUrl:
|
||||
|
||||
result = svc.get_download_url("uploads/video.mp4")
|
||||
|
||||
svc.bucket.sign_url.assert_called_once_with("GET", "uploads/video.mp4", 3600, slash_safe=True)
|
||||
svc.bucket.sign_url.assert_called_once_with("GET", "uploads/video.mp4", 3600)
|
||||
assert "signed-url" in result
|
||||
|
||||
def test_returns_raw_url_when_bucket_none(self):
|
||||
|
||||
@@ -250,34 +250,3 @@ class TestMultiplierConsistency:
|
||||
resp = check_points(body=body, current_user=cu, db=db)
|
||||
expected = calculate_points_cost(scene, is_member=False, quantity=1, duration_minutes=1)
|
||||
assert resp.required_points == expected, f"{scene}: got {resp.required_points}, expected {expected}"
|
||||
|
||||
# ── GET /points/balance 返回后端真实积分开关 credits_enabled ──────────
|
||||
|
||||
|
||||
class TestBalanceCreditsEnabled:
|
||||
def _call_balance(self, enabled):
|
||||
from app.api.routes import points as points_routes
|
||||
|
||||
svc = MagicMock()
|
||||
svc.get_or_create_account.return_value = {
|
||||
"balance": 0,
|
||||
"total_earned": 0,
|
||||
"total_spent": 0,
|
||||
}
|
||||
cu = _make_cu()
|
||||
db = MagicMock()
|
||||
with (
|
||||
patch("app.api.routes.points._get_service", return_value=svc),
|
||||
patch("app.api.routes.points._credits_enabled", return_value=enabled),
|
||||
):
|
||||
return points_routes.get_balance(current_user=cu, db=db)
|
||||
|
||||
def test_balance_credits_enabled_false_when_free_pass(self):
|
||||
"""免费期(开关关闭)时 credits_enabled=False,前端应跳过余额预校验。"""
|
||||
resp = self._call_balance(False)
|
||||
assert resp.credits_enabled is False
|
||||
|
||||
def test_balance_credits_enabled_true_when_enabled(self):
|
||||
"""收费期(开关开启)时 credits_enabled=True。"""
|
||||
resp = self._call_balance(True)
|
||||
assert resp.credits_enabled is True
|
||||
|
||||
@@ -361,7 +361,7 @@ class TestGetDownloadUrlFallback:
|
||||
|
||||
result = service.get_download_url("videos/test.mp4", expires_seconds=7200)
|
||||
|
||||
mock_bucket.sign_url.assert_called_once_with("GET", "videos/test.mp4", 7200, slash_safe=True)
|
||||
mock_bucket.sign_url.assert_called_once_with("GET", "videos/test.mp4", 7200)
|
||||
assert result == "https://signed-url.com/file?sig=abc"
|
||||
|
||||
def test_sign_url_exception_falls_back_to_public_url(self):
|
||||
|
||||
@@ -65,7 +65,6 @@ def _make_job(job_id: str = "job-1", user_id: str = "u1", status: str = "pending
|
||||
"image_analysis": None,
|
||||
"storyboard": None,
|
||||
"generated_copy_text": "",
|
||||
"language": "zh-CN",
|
||||
"voice_id": "",
|
||||
"voice_source": "",
|
||||
"voice_mode": "global",
|
||||
|
||||
@@ -8,15 +8,11 @@ Bug4: 错误事件按阶段区分(_mark_failed_and_notify 传正确 stage)
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# 仓库根目录(本文件位于 tests/unit/,向上两级)
|
||||
BASE = str(Path(__file__).resolve().parents[2])
|
||||
|
||||
|
||||
def _auth_user(uid: str = "u1"):
|
||||
return SimpleNamespace(user=SimpleNamespace(id=uid))
|
||||
@@ -56,7 +52,6 @@ def _make_job(job_id: str = "job-1", user_id: str = "u1", status: str = "pending
|
||||
"storyboard": None,
|
||||
"copy_result": {"voiceover_script": "测试口播", "shots": [{"clip_id": 1}]},
|
||||
"generated_copy_text": "",
|
||||
"language": "zh-CN",
|
||||
"voice_id": "",
|
||||
"voice_source": "",
|
||||
"voice_mode": "global",
|
||||
|
||||
Reference in New Issue
Block a user