test(models): 加 3 个 Schema 关系烟测

按 W2 plan Task 9 落地:
- insertIndicatorWithReportRelationship: 验证 Indicator.report 反向关系
  双向可达(report.indicators 也能找到)
- cascadeDeleteReportRemovesIndicators: 删 Report 触发 cascade,旗下
  Indicator 一并被清理(对应"永久删除"语义)
- chatTurnPersistsReferencedIDs: ChatTurn 的 referencedIndicatorIDs
  作为 [String] 字段正确持久化

全部用 in-memory ModelContainer 隔离,无副作用。

注:文件需用户在 Xcode 拖入 体己Tests target 后 ⌘U 跑测试。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
link2026
2026-05-25 18:23:45 +08:00
parent a3e758cf83
commit 57536e5319

View File

@@ -0,0 +1,79 @@
import Testing
import SwiftData
import Foundation
@testable import
struct ModelsSchemaTests {
private func makeContainer() throws -> ModelContainer {
let schema = Schema([
Indicator.self,
Report.self,
DiaryEntry.self,
Asset.self,
ChatTurn.self,
])
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
return try ModelContainer(for: schema, configurations: [config])
}
@Test func insertIndicatorWithReportRelationship() throws {
let container = try makeContainer()
let ctx = ModelContext(container)
let report = Report(title: "春检", type: .checkup, reportDate: .now)
let indicator = Indicator(
name: "ALT",
value: "32",
unit: "U/L",
range: "9-50",
status: .normal,
report: report
)
ctx.insert(report)
ctx.insert(indicator)
try ctx.save()
#expect(report.indicators.count == 1)
#expect(indicator.report?.title == "春检")
}
@Test func cascadeDeleteReportRemovesIndicators() throws {
let container = try makeContainer()
let ctx = ModelContext(container)
let report = Report(title: "春检", type: .checkup, reportDate: .now)
let indicator = Indicator(
name: "ALT", value: "32", unit: "U/L", range: "9-50",
status: .normal, report: report
)
ctx.insert(report)
ctx.insert(indicator)
try ctx.save()
ctx.delete(report)
try ctx.save()
let remaining = try ctx.fetch(FetchDescriptor<Indicator>())
#expect(remaining.isEmpty)
}
@Test func chatTurnPersistsReferencedIDs() throws {
let container = try makeContainer()
let ctx = ModelContext(container)
let turn = ChatTurn(
question: "我的 LDL 怎么样?",
answer: "近 3 个月 LDL 偏高 [1]",
referencedIndicatorIDs: ["abc"],
referencedReportIDs: [],
decodeRate: 24.3
)
ctx.insert(turn)
try ctx.save()
let all = try ctx.fetch(FetchDescriptor<ChatTurn>())
#expect(all.count == 1)
#expect(all.first?.referencedIndicatorIDs == ["abc"])
}
}