Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/developer.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ git diff -- packages/contracts/openapi.json frontend/src/api/schema.d.ts

旧版 FastAPI 基线保存在 `tests-ts/contracts/fastapi-openapi.json`。现有兼容路由不能无意删除或改方法;有意的破坏性变更应单独说明并更新契约测试。

### API 响应契约盘点

在正式收紧响应 schema 之前,先维护 `tests-ts/contracts/response-inventory.ts`,并在 `tests-ts/contracts/fixtures/` 保存脱敏的响应和事件样例。HTTP 边界测试必须通过 Hono `app.request()` 验证状态码、Content-Type、错误格式和当前字段形状;不要只调用 Core 内部用例。新增或修改 API 时,先更新 inventory、fixture 和边界测试,再在后续改动中更新 `packages/contracts` 的正式 Zod schema。

## 测试与构建

提交前的默认门槛:
Expand Down
9 changes: 9 additions & 0 deletions tests-ts/contracts/fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const responseFixtureRoot = 'tests-ts/contracts/fixtures/responses/'

export async function loadResponseFixture<T = unknown>(filename: string): Promise<T> {
return await Bun.file(`${responseFixtureRoot}${filename}`).json() as T
}

export async function loadTextFixture(filename: string): Promise<string> {
return await Bun.file(`tests-ts/contracts/fixtures/${filename}`).text()
}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/copilot/events.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"type":"started","session_id":"session-1"},{"type":"asr_interim","text":"请介绍"},{"type":"asr_final","text":"请介绍一下项目"},{"type":"progress","progress":0.5,"message":"分析中"},{"type":"error","message":"连接已关闭"}]
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/auth-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"allow_registration":false}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/auth-response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"token":"fixture-token","user":{"id":"user-a","email":"user@example.com","name":"Fixture User","is_admin":false}}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/change-password.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"status":"ok"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"prep_id":"prep-1"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"status":"running","progress":"正在分析","error":"","company":"示例公司","position":"后端工程师"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/copilot-preps.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/copilot-tree.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"root_nodes":[],"nodes":{},"phase_order":[]}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/data-import.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"files_copied":0,"files_skipped":0,"db_inserted":0,"db_skipped":0}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/due-reviews.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/interview-chat.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"resume-session-1","message":"好的,请介绍一下你的项目。","is_finished":false}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/interview-draft.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"topic-session-1","status":"ongoing","saved":true}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"topic-session-1","mode":"topic_drill","status":"pending"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"items":[],"total":0}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"preview":{"company":"示例公司","position":"后端工程师","role_summary":"后端服务开发","focus_areas":[],"likely_question_groups":[],"resume_alignment":{"resume_used":false,"matching_evidence":[],"risk_gaps":[],"recommended_stories":[]},"prep_priorities":[],"question_blueprint":[],"jd_excerpt":""}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"resume-session-1","mode":"resume","topic":null,"status":"ongoing","review_error":null,"transcript":[],"questions":[],"target_role":"后端工程师","job_description":"","meta":{},"can_continue":true,"is_finished":false,"has_review":false}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"topic-session-1","mode":"topic_drill","status":"pending"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"topic-session-1","mode":"topic_drill","review":"# 复盘","scores":[],"weak_points":[],"overall":{},"status":"reviewed"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"jd-session-1","mode":"jd_prep","questions":[],"preview":{},"company":"示例公司","position":"后端工程师","meta":{}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"resume-session-1","mode":"resume","topic":null,"target_role":"后端工程师","job_description":"","message":"请先做自我介绍"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"topic-session-1","mode":"topic_drill","topic":"typescript","questions":[{"id":1,"question":"解释 TypeScript 的结构类型系统","difficulty":3}]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"content":"常见问题"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"filename":"core.md"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/knowledge-files.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"filename":"core.md","content":"# TypeScript"}]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"content":"# Generated knowledge"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/ok.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"conversation_id":"conversation-1","title":"复习建议","message":{"role":"assistant","content":"建议先复习类型系统。","created_at":"2026-01-01T00:00:00.000Z","sources":[]}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"conversation_id":"conversation-1","title":"复习建议","messages":[],"created_at":"2026-01-01T00:00:00.000Z","updated_at":"2026-01-01T00:00:00.000Z"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"items":[]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"document_id":"document-1","filename":"notes.md","extension":".md","size_bytes":128,"status":"ready","chunk_count":1}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"items":[],"supported_extensions":[".md"],"max_upload_bytes":20971520}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"point":"跨领域机制解释停留在表面","confidence":0.8,"user_acknowledged":true}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/profile.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"","target_role":"","updated_at":"","last_consolidation_at":"","topic_mastery":{},"weak_points":[],"strong_points":[],"behavior_signals":{},"communication":{"style":"","habits":[],"suggestions":[]},"thinking_patterns":{"strengths":[],"gaps":[]},"stats":{"total_sessions":0,"resume_sessions":0,"drill_sessions":0,"job_prep_sessions":0,"avg_score":0,"score_history":[]},"due_reviews":[]}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/question-graph.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"nodes":[],"links":[]}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/quota-status.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"source":"user","used":0,"limit":null,"unit":"token","window":"day"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"session_id":"recording-session-1","status":"pending"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"transcript":"面试官:请介绍项目","segments":[]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"reference_answer":"可以从类型兼容性和结构约束两个方面回答。","cached":false}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/resume-parsed.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"parsed":{"basic":{"name":"Fixture User"},"education":[],"experience":[],"projects":[],"skills":[]}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"has_resume":false}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"has_resume":true,"filename":"resume.pdf","size":1024}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/resume-uploaded.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"filename":"resume.pdf","size":1024}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"task_id":"retro_typescript_user-a","status":"pending"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/service-info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"service":"TechSpar","version":"0.4.0"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/settings-probe.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/settings-update.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"embedding_changed":false}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/settings-view.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"llm":{"api_base":"","api_key":"","model":"","temperature":0.7,"compatibility":"generic","use_platform":false},"embedding":{"backend":""},"services":{"dashscope_api_key":"","tavily_api_key":"","oss_access_key_id":"","oss_access_key_secret":"","oss_bucket":"","oss_endpoint":""},"system":{"allow_registration":false},"training":{"num_questions":10,"divergence":3},"is_admin":false,"configured":{"llm":false,"embedding":false},"platform":{"llm":false,"embedding":false},"source":"user","last_reindex_at":""}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/target-role.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"target_role":"后端工程师"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/task-done.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"status":"done","type":"drill_review"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/task-error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"status":"error","type":"drill_review","error":"任务失败"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/task-pending.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"status":"pending","type":"drill_review"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/topic-created.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"key":"typescript"}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/topic-history.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/topics.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"typescript":{"name":"TypeScript","icon":"code","dir":"typescript"}}
1 change: 1 addition & 0 deletions tests-ts/contracts/fixtures/responses/transcription.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"text":"这是测试转写"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"ok":true,"enrolled_at":"2026-01-01T00:00:00.000Z"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"configured":false,"enrolled":false,"enrolled_at":null,"speaker_nick":null}
3 changes: 3 additions & 0 deletions tests-ts/contracts/fixtures/sse/interview-chat-stream.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data: {"token":"你好"}

data: {"done":true,"is_finished":false}
3 changes: 3 additions & 0 deletions tests-ts/contracts/fixtures/sse/rebuild-index-stream.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data: {"progress":0.5,"message":"正在索引"}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 使用重建索引实际输出的 SSE 事件结构

这个样例使用 { progress, message },但 SettingsOperationsService.rebuildIndex() 实际输出 { completed, total, label, status };完成事件还带有 rebuilt 和 last_rebuild_at。经真实 service 的 HTTP SSE 请求确认,当前样例并不代表该接口的返回结构。现有 inventory 测试只检查这个文件存在,因此无法捕获这类偏差。请更新样例,并新增 /api/settings/rebuild-index 的 HTTP 边界测试,将解析后的真实事件与 fixture 对照(时间字段可规范化)。


data: {"done":true}
92 changes: 92 additions & 0 deletions tests-ts/contracts/http-response-boundaries.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { describe, expect, test } from 'bun:test'
import { ProviderResponseError, type InterviewUseCases, type ProfileUseCases } from '@techspar/core'
import { loadResponseFixture } from './fixture.ts'
import { boundaryApp, jsonHeaders } from './test-app.ts'

describe('HTTP response boundary inventory', () => {
test('keeps service info response shape', async () => {
const response = await boundaryApp().request('/api/')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('application/json')
expect(await response.json()).toMatchObject({ service: 'TechSpar', version: expect.any(String) })
})

test('records the current dynamic topic-drill start response', async () => {
const interview = {
async start() { return loadResponseFixture('interview-start-topic.json') },
} as unknown as InterviewUseCases
const response = await boundaryApp({ interview }).request('/api/interview/start', {
method: 'POST', headers: jsonHeaders, body: JSON.stringify({ mode: 'topic_drill', topic: 'typescript' }),
})
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('application/json')
expect(await response.json()).toMatchObject({
session_id: expect.any(String), mode: 'topic_drill', topic: expect.any(String), questions: expect.any(Array),
})
})

test('records the current profile response shape', async () => {
const profile = {
async get() { return loadResponseFixture('profile.json') },
} as unknown as ProfileUseCases
const response = await boundaryApp({ profile }).request('/api/profile', { headers: { authorization: jsonHeaders.authorization } })
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ weak_points: expect.any(Array), stats: expect.any(Object) })
})

test('keeps task status responses parseable at the HTTP boundary', async () => {
const interview = {
async task() { return loadResponseFixture('task-pending.json') },
} as unknown as InterviewUseCases
const response = await boundaryApp({ interview }).request('/api/tasks/task-1', {
headers: { authorization: jsonHeaders.authorization },
})
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ status: 'pending', type: 'drill_review' })
})

test('preserves the current interview SSE framing', async () => {
const interview = {
async *chatStream() {
yield { token: '你好' }
yield { done: true, is_finished: false }
},
} as unknown as InterviewUseCases
const response = await boundaryApp({ interview }).request('/api/interview/chat/stream', {
method: 'POST', headers: jsonHeaders, body: JSON.stringify({ session_id: 'session-1', message: '开始' }),
})
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/event-stream')
const body = await response.text()
expect(body).toContain('data: {"token":"你好"}')
expect(body).toContain('data: {"done":true,"is_finished":false}')
})

test('preserves provider errors at the HTTP boundary', async () => {
const interview = {
async start() { throw new ProviderResponseError('模型服务响应无效') },
} as unknown as InterviewUseCases
const response = await boundaryApp({ interview }).request('/api/interview/start', {
method: 'POST', headers: jsonHeaders, body: JSON.stringify({ mode: 'topic_drill', topic: 'typescript' }),
})
expect(response.status).toBe(502)
expect(await response.json()).toEqual({ detail: '模型服务响应无效', code: 'provider_response_error' })
})

test('returns the existing validation error format', async () => {
const response = await boundaryApp().request('/api/auth/login', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}),
})
expect(response.status).toBe(422)
expect(response.headers.get('content-type')).toContain('application/json')
expect(await response.json()).toMatchObject({ detail: expect.any(Array) })
})

test('returns JSON 401 for missing authentication', async () => {
// Register the route so the request reaches the authentication boundary.
const response = await boundaryApp({ profile: {} as ProfileUseCases }).request('/api/profile')
expect(response.status).toBe(401)
expect(response.headers.get('content-type')).toContain('application/json')
expect(await response.json()).toEqual({ detail: 'Invalid or expired token' })
})
})
6 changes: 6 additions & 0 deletions tests-ts/contracts/openapi-parity.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
import { createApp, type AppDependencies } from '../../apps/api/src/app.ts'
import { inventoryOperations } from './response-inventory.ts'

type Operation = {
parameters?: unknown[]
Expand Down Expand Up @@ -78,4 +79,9 @@ describe('FastAPI to Hono OpenAPI parity', () => {
'multipart/form-data',
])
})

test('keeps every generated HTTP operation in the response inventory', async () => {
const { current } = await loadSpecs()
expect(inventoryOperations).toEqual(operations(current))
})
})
45 changes: 45 additions & 0 deletions tests-ts/contracts/response-inventory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, expect, test } from 'bun:test'
import { inventoryOperations, responseInventory } from './response-inventory.ts'

describe('API response inventory', () => {
test('has unique HTTP operations', () => {
expect(new Set(inventoryOperations).size).toBe(inventoryOperations.length)
})

test('records a fixture for every JSON response family', () => {
const missing = responseInventory
.filter((entry) => entry.transport === 'json' && !entry.fixture)
.map((entry) => entry.operation)
expect(missing).toEqual([])
})

test('points only to checked-in fixture files', async () => {
const missing = [] as string[]
for (const entry of responseInventory) {
if (!entry.fixture) continue
const root = entry.fixture.includes('/') ? 'tests-ts/contracts/fixtures' : 'tests-ts/contracts/fixtures/responses'
const path = `${root}/${entry.fixture}`
if (!await Bun.file(path).exists()) missing.push(path)
}
expect(missing).toEqual([])
})

test('keeps JSON response fixtures parseable', async () => {
const invalid = [] as string[]
for (const entry of responseInventory) {
if (!entry.fixture || entry.fixture.includes('/')) continue
try { await Bun.file(`tests-ts/contracts/fixtures/responses/${entry.fixture}`).json() }
catch { invalid.push(entry.fixture) }
}
expect(invalid).toEqual([])
})

test('marks current dynamic response surfaces for later tightening', () => {
const dynamic = responseInventory.filter((entry) => entry.dynamic).map((entry) => entry.operation)
expect(dynamic).toEqual(expect.arrayContaining([
'POST /api/interview/start',
'GET /api/profile',
'GET /api/copilot/prep/{prep_id}',
]))
})
})
Loading