import Foundation import Testing @testable import suixinkan /// 正式课程的按需资源、前台计时和幂等恢复;只使用内存替身,不修改真实学员记录。 @Suite("正式培训课程与读时") @MainActor struct TrainingRemoteReadingTests { private func source(seconds: Int = 0) -> TrainingDataStub { var configuration = TrainingDataStub.Configuration() configuration.readingSeconds = seconds return TrainingDataStub(configuration: configuration) } private func model(_ source: TrainingDataStub) -> TrainingRemoteReadingViewModel { TrainingRemoteReadingViewModel(taskID: "task_1", service: source, now: { TrainingRemoteFixtures.now }) } private func bind(_ server: TrainingReadingReplyController, to source: TrainingDataStub) async { await source.configure { $0.progressHandler = { _ in await server.progress() } $0.startReadingHandler = { try await server.create(requestID: $0) } $0.heartbeatHandler = { try await server.confirm($0) } } } private func loadRendered(_ model: TrainingRemoteReadingViewModel) async { await model.load() if let id = model.currentAttachmentID, let previewID = model.attachmentPreviewID { #expect(model.markAttachmentRendered(id: id, previewID: previewID)) } } /// 首屏只读取一页附件并授权首项,不请求已经停用的小节 HTML。 @Test("首次仅请求附件第一页并授权首项,不加载小节 HTML") func lazyCourseResources() async { let source = source() await source.configure { $0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) } $0.attachmentsHandler = { _ in TrainingCursorPage(items: (1...20).map { TrainingRemoteFixtures.attachment(id: "file_\($0)") }, nextCursor: "next", hasMore: true, serverTime: nil) } } let model = model(source) await model.load() let calls = await source.calls #expect(model.attachments.count == 20) #expect(model.currentAttachmentID == "file_1") #expect(model.currentAttachmentLink?.id == "file_1") #expect(calls.filter { $0.name == "attachments" }.count == 1) #expect(calls.first { $0.name == "attachments" }?.limit == 20) #expect(calls.filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1"]) #expect(!calls.contains { ["sections", "section", "paper", "questions", "draft", "attempts"].contains($0.name) }) #expect(!model.isAttachmentRendered) } /// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。 @Test("每五秒上报且门槛由后端确认,完成后停止会话") func batchedHeartbeatAndCompletion() async { let source = source() let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } #expect(await source.heartbeats.isEmpty) #expect(model.progress?.readingSeconds == 0) for second in 5...20 { await model.recordVisibleTime(at: Double(second)) } let calls = await source.heartbeats #expect(calls.map(\.activeSecondsTotal) == [5, 10, 15, 20]) #expect(calls.map(\.sequence) == [1, 2, 3, 4]) #expect(calls.last?.final == true) #expect(model.progress?.readingCompleted == true) #expect(!model.isReading) #expect(model.remainingSeconds == 0) } /// 已保存读时不混入会话累计;不足五秒的门槛片段也即时确认。 @Test("历史十二秒加新会话八秒,心跳总数仍从零开始") func historyAndSessionAreSeparate() async { let source = source(seconds: 12) let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...8 { await model.recordVisibleTime(at: Double(second)) } let calls = await source.heartbeats #expect(calls.map(\.activeSecondsTotal) == [5, 8]) #expect(calls.last?.final == true) #expect(model.progress?.readingSeconds == 20) #expect(model.progress?.readingCompleted == true) } /// 后台间隔与未满秒片段均不补算,重开会话使用独立序号和累计秒数。 @Test("暂停后长时间停留不补读时,恢复会话从零计时") func pauseDoesNotCountBackgroundTime() async { let source = source() let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } model.pauseReading() await model.flush() await model.recordVisibleTime(at: 999) await model.startReading(at: 1000) await model.recordVisibleTime(at: 1000.5) await model.recordVisibleTime(at: 1001) await model.recordVisibleTime(at: 1002) model.pauseReading() await model.flush() let calls = await source.heartbeats #expect(calls.map(\.activeSecondsTotal) == [3, 2]) #expect(calls.map(\.sequence) == [1, 1]) #expect(calls.allSatisfy { $0.final }) #expect(calls[0].sessionID != calls[1].sessionID) #expect(model.progress?.readingSeconds == 5) } /// 创建已成功但响应丢失时,同一创建键恢复原会话。 @Test("创建会话丢响应重试沿用 requestID") func createResponseLossUsesSameRequestID() async { let source = source() let server = TrainingReadingReplyController(loseCreateResponse: true) await bind(server, to: source) let model = model(source) await loadRendered(model) await model.startReading(at: 0) #expect(model.readingErrorMessage != nil) await model.startReading(at: 10) let requests = await source.startReadingRequests #expect(requests.count == 2) #expect(requests[0] == requests[1]) #expect(model.isReading) #expect(model.activeSecondsTotal == 0) } /// 服务端已接受的普通心跳丢响应,不能改变序号或负载再次累计。 @Test("心跳丢响应同序号同负载重试,不重复增记") func heartbeatResponseLossIsIdempotent() async { let source = source() let server = TrainingReadingReplyController(loseHeartbeatResponse: true) await bind(server, to: source) let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } #expect(model.progress?.readingSeconds == 0) await model.flush() let calls = await source.heartbeats #expect(calls.count == 2) #expect(calls[0] == calls[1]) #expect(calls[0].final == false) #expect(model.progress?.readingSeconds == 5) #expect(await server.progress().readingSeconds == 5) } /// 最终关闭请求同样冻结 final 和累计秒数,重试不能改成普通心跳。 @Test("final 关闭丢响应保持原 final 负载,之后使用新会话") func finalResponseLossKeepsPayload() async { let source = source() let server = TrainingReadingReplyController(loseHeartbeatResponse: true) await bind(server, to: source) let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } model.pauseReading() await model.flush() #expect(model.readingErrorMessage != nil) await model.flush(final: true) let calls = await source.heartbeats #expect(calls.count == 2) #expect(calls[0] == calls[1]) #expect(calls[0].final) #expect(model.progress?.readingSeconds == 3) await model.startReading(at: 100) let requests = await source.startReadingRequests #expect(requests.count == 2) #expect(requests[0] != requests[1]) #expect(model.activeSecondsTotal == 0) } /// 暂停发生在网络请求中间时,先确认旧负载,再以新序号关闭。 @Test("普通心跳请求中途暂停,确认后再发送 final") func pauseDuringHeartbeatFinishesSequentially() async { let source = source() let gate = TrainingReadingHeartbeatGate() await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } } let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } let operation = Task { await model.recordVisibleTime(at: 5) } await gate.waitUntilRequested() model.pauseReading() let closing = Task { await model.flush() } #expect(await source.heartbeats.count == 1) await gate.release() await operation.value await closing.value let calls = await source.heartbeats #expect(calls.count == 2) #expect(calls[0].sequence == 1 && !calls[0].final) #expect(calls[1].sequence == 2 && calls[1].final) #expect(calls[0].activeSecondsTotal == calls[1].activeSecondsTotal) #expect(!model.isReading) #expect(model.progress?.readingSeconds == 5) } /// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。 @Test("final 请求仍在飞时恢复阅读,串行等待关闭后启动") func resumeWaitsForFinalConfirmation() async { let source = source() let server = TrainingReadingReplyController() let gate = TrainingReadingHeartbeatGate() await bind(server, to: source) await source.configure { $0.heartbeatHandler = { call in _ = await gate.confirm(call) return try await server.confirm(call) } } let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } let closing = Task { await model.flush(final: true) } await gate.waitUntilRequested() let probe = TrainingReadingResumeProbe() let resuming = Task { probe.started = true await model.startReading(at: 100) probe.finished = true } while !probe.started { await Task.yield() } #expect(!probe.finished) #expect(await source.startReadingRequests.count == 1) await gate.release() await closing.value await resuming.value #expect(model.isReading) #expect(await source.startReadingRequests.count == 2) #expect(model.activeSecondsTotal == 0) #expect(model.progress?.readingSeconds == 3) await model.recordVisibleTime(at: 101) #expect(model.activeSecondsTotal == 1) } /// 任务截止后刷新只读资格,不可通过重试重新累计有效读时。 @Test("150102刷新为只读资格,不能重新建立学习会话") func notWritableRefreshesReadOnlyState() async { let source = source() let model = model(source) await loadRendered(model) await model.startReading(at: 0) let saved = TrainingRemoteFixtures.progress(seconds: 7) let readOnly = TrainingProgressSnapshot(taskID: saved.taskID, readingSeconds: saved.readingSeconds, requiredReadingSeconds: saved.requiredReadingSeconds, completedSectionCount: saved.completedSectionCount, sectionCount: saved.sectionCount, progressPercent: saved.progressPercent, readingCompleted: false, learnerStatus: .pendingExam, completedAt: nil, hasDraft: false, canViewCourse: true, canStudy: false, canStartExam: false, canRetry: false, blockReason: "closed", serverTime: saved.serverTime) await source.configure { $0.heartbeatHandler = { _ in throw TrainingRemoteError.notWritable("arbitrary closed message") } $0.progressHandler = { _ in readOnly } } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } #expect(!model.canStudy) #expect(model.progress?.blockReason == "closed") #expect(model.currentAttachmentLink != nil) await model.startReading(at: 100) #expect(await source.startReadingRequests.count == 1) #expect(!model.isReading) } /// 稳定权限拒绝清空正文与进度,让页面立即退出而非保留旧内容。 @Test("账号失效或培训权限撤回时清内容退出", arguments: [ TrainingRemoteError.accountInvalid("account no longer eligible"), TrainingRemoteError.forbidden("assignment revoked") ]) func accessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async { let source = source() let model = model(source) await loadRendered(model) await model.startReading(at: 0) await source.configure { $0.heartbeatHandler = { _ in throw failure } } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } #expect(model.isInvalidated) #expect(model.currentAttachmentLink == nil) #expect(model.progress == nil) #expect(model.attachments.isEmpty) #expect(!model.isReading) } /// 只按稳定业务码恢复过期与冲突,不依据错误文案。 @Test("会话过期或冲突先读权威进度,重建新会话序号", arguments: [ TrainingRemoteError.sessionExpired("arbitrary expired message"), TrainingRemoteError.sessionConflict("arbitrary conflict message") ]) func expiredSessionRestoresProgress(_ failure: TrainingRemoteError) async { let source = source() let server = TrainingReadingReplyController(nextFailure: failure) await bind(server, to: source) let model = model(source) await loadRendered(model) await model.startReading(at: 0) for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } #expect(model.isReading) #expect(model.activeSecondsTotal == 0) #expect(await source.startReadingRequests.count == 2) for second in 6...10 { await model.recordVisibleTime(at: Double(second)) } let calls = await source.heartbeats #expect(calls.count == 2) #expect(calls[0].sessionID != calls[1].sessionID) #expect(calls[1].sequence == 1) #expect(calls[1].activeSecondsTotal == 5) #expect(model.progress?.readingSeconds == 5) #expect((await source.calls).filter { $0.name == "progress" }.count >= 2) } /// 授权请求挂起时切身份,旧短链不能重新打开已经关闭的页面。 @Test("身份切换丢弃迟到附件授权和权威进度") func identityChangeDiscardsLateAttachment() async { let source = source() let gate = TrainingReadingAttachmentGate() await source.configure { $0.attachmentURLHandler = { _ in await gate.link() } } let model = model(source) let operation = Task { await model.load() } await gate.waitUntilRequested() model.invalidate() await gate.release() await operation.value #expect(model.isInvalidated) #expect(model.task == nil) #expect(model.currentAttachment == nil) #expect(model.currentAttachmentLink == nil) #expect(model.attachmentPreviewID == nil) #expect(model.progress == nil) #expect(model.attachments.isEmpty) } /// 后续附件页需要用户主动读取,分页不能提前授权其余文档。 @Test("附件目录主动分页且只在选择时授权后续附件") func attachmentsAreLazyAndAuthorized() async { let source = source(seconds: 20) await source.configure { $0.attachmentsHandler = { cursor in let id = cursor == nil ? "file_1" : "file_2" return TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: id)], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil) } } let model = model(source) await model.load() await model.loadAttachments() await model.loadAttachments() #expect((await source.calls).filter { $0.name == "attachments" }.count == 1) #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1) await model.loadAttachments(loadMore: true) #expect(model.attachments.count == 2) #expect((await source.calls).filter { $0.name == "attachments" }.last?.cursor == "next") #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1) await model.selectAttachment(id: "file_2") #expect(model.currentAttachmentID == "file_2") #expect(model.currentAttachmentLink?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600)) #expect((await source.calls).filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1", "file_2"]) #expect(!model.isAttachmentRendered) } /// 分页失败只提示列表错误,不能把已显示文件变成失败态或丢弃已累计秒数。 @Test("附件分页失败可重试,当前文档继续阅读且成功后清提示") func attachmentPaginationErrorDoesNotInterruptReading() async throws { let source = source() await source.configure { $0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil) } } let model = model(source) await loadRendered(model) let previewID = try #require(model.attachmentPreviewID) let link = try #require(model.currentAttachmentLink) await model.startReading(at: 0) await model.recordVisibleTime(at: 1) await source.configure { $0.attachmentsHandler = { _ in throw URLError(.timedOut) } } await model.loadAttachments(loadMore: true) #expect(model.attachmentListErrorMessage != nil) #expect(model.attachmentErrorMessage == nil && model.errorMessage == nil) #expect(model.isAttachmentRendered && model.isReading && model.canStudy) #expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID) #expect(model.attachments.count == 1 && model.hasMoreAttachments) #expect(model.markAttachmentRendered(id: "file_1", previewID: previewID)) await model.recordVisibleTime(at: 2) #expect(model.activeSecondsTotal == 2) await source.configure { $0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil) } } await model.loadAttachments(loadMore: true) #expect(model.attachmentListErrorMessage == nil && model.errorMessage == nil) #expect(model.attachments.map(\.id) == ["file_1", "file_2"]) #expect(!model.hasMoreAttachments) #expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID) #expect(model.isAttachmentRendered && model.isReading) await model.recordVisibleTime(at: 3) model.pauseReading() await model.flush() let heartbeats = await source.heartbeats #expect(heartbeats.count == 1) #expect(heartbeats.first?.activeSecondsTotal == 3 && heartbeats.first?.final == true) #expect(await source.startReadingRequests.count == 1) let calls = await source.calls #expect(calls.filter { $0.name == "attachments" }.map(\.cursor) == [nil, "next", "next"]) #expect(calls.filter { $0.name == "attachmentURL" }.count == 1) } /// 授权被撤回不是普通分页故障,必须清理已经可读的文件并立即停止学习。 @Test("附件分页返回账号或权限失效时仍清内容退出", arguments: [ TrainingRemoteError.accountInvalid("account no longer eligible"), TrainingRemoteError.forbidden("assignment revoked") ]) func attachmentPaginationAccessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async { let source = source() await source.configure { $0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil) } } let model = model(source) await loadRendered(model) await model.startReading(at: 0) await source.configure { $0.attachmentsHandler = { _ in throw failure } } await model.loadAttachments(loadMore: true) #expect(model.isInvalidated) #expect(!model.isReading && !model.isAttachmentRendered) #expect(model.attachments.isEmpty && model.currentAttachmentLink == nil) #expect(model.attachmentListErrorMessage == nil) } /// 只有文档下载与渲染都结束并由页面确认后才建立学习会话。 @Test("附件授权不代表已展示,渲染确认前不能累计读时") func authorizedAttachmentWaitsForRendering() async throws { let source = source() let model = model(source) await model.load() #expect(model.currentAttachmentLink != nil) await model.startReading(at: 0) await model.recordVisibleTime(at: 100) #expect(await source.startReadingRequests.isEmpty) #expect(await source.heartbeats.isEmpty) let previewID = try #require(model.attachmentPreviewID) #expect(!model.markAttachmentRendered(id: "another-file", previewID: previewID)) #expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID())) #expect(model.markAttachmentRendered(id: "file_1", previewID: previewID)) await model.startReading(at: 200) await model.recordVisibleTime(at: 201) #expect(model.isReading) #expect(model.activeSecondsTotal == 1) #expect(await source.startReadingRequests.count == 1) } /// 没有课程文档时保留元信息空态,不请求 HTML,也不能通过空白页获得进度。 @Test("无附件保留课程元信息但不建立会话或回退 HTML") func missingAttachmentDoesNotCountReading() async { let source = source() await source.configure { $0.attachmentsHandler = { _ in TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil) } } let model = model(source) await model.load() await model.startReading(at: 0) await model.recordVisibleTime(at: 1000) #expect(model.task != nil && model.course != nil && model.progress != nil) #expect(model.hasLoadedAttachments) #expect(model.currentAttachment == nil) #expect(model.currentAttachmentLink == nil) #expect(!model.isAttachmentRendered) #expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID())) #expect(!(await source.calls).contains { ["section", "sections", "attachmentURL", "startReading", "heartbeat"].contains($0.name) }) } /// 授权失败仍展示课程规则和附件名,重试成功后也要等待实际渲染。 @Test("授权失败可重试同一附件,课程元信息不丢失") func authorizationFailureKeepsMetadataForRetry() async throws { let source = source() await source.configure { $0.attachmentURLHandler = { _ in throw URLError(.timedOut) } } let model = model(source) await model.load() #expect(model.task != nil && model.course != nil && model.progress != nil) #expect(model.currentAttachmentID == "file_1") #expect(model.currentAttachmentLink == nil) #expect(model.attachmentErrorMessage != nil) await model.startReading(at: 0) #expect(await source.startReadingRequests.isEmpty) let failedPreviewID = try #require(model.attachmentPreviewID) await source.configure { $0.attachmentURLHandler = nil } await model.selectAttachment(id: "file_1") let nextPreviewID = try #require(model.attachmentPreviewID) #expect(nextPreviewID != failedPreviewID) #expect(model.currentAttachmentLink != nil) #expect(model.attachmentErrorMessage == nil) #expect(!model.markAttachmentRendered(id: "file_1", previewID: failedPreviewID)) #expect(model.markAttachmentRendered(id: "file_1", previewID: nextPreviewID)) } /// 预览失败停止当前片段,进度刷新不得误清错误或恢复读时。 @Test("附件预览失败停止读时,错误跨进度刷新保留") func previewFailureStopsReadingAndSurvivesProgressRefresh() async throws { let source = source() let model = model(source) await loadRendered(model) let previewID = try #require(model.attachmentPreviewID) await model.startReading(at: 0) for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } model.reportAttachmentFailure(id: "file_1", previewID: previewID, message: "文档加载失败") #expect(!model.isReading && !model.isAttachmentRendered) await model.flush() await model.refreshProgress() #expect(model.attachmentErrorMessage == "文档加载失败") #expect(model.errorMessage == "文档加载失败") #expect(!model.markAttachmentRendered(id: "file_1", previewID: previewID)) await model.startReading(at: 100) await model.recordVisibleTime(at: 101) let calls = await source.heartbeats #expect(calls.count == 1) #expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true) #expect(await source.startReadingRequests.count == 1) #expect(model.progress?.readingSeconds == 3) } /// 切文档关闭旧片段,旧下载成功或失败回调都不能改变新文档。 @Test("切附件先 final 保存,旧预览回调无效,新文档重新计时") func switchingAttachmentClosesReadingAndRejectsLatePreview() async throws { let source = source() await source.configure { $0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(), TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil) } } let model = model(source) await loadRendered(model) let oldPreviewID = try #require(model.attachmentPreviewID) await model.startReading(at: 0) for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } await model.selectAttachment(id: "file_2") let calls = await source.heartbeats #expect(calls.count == 1) #expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true) #expect(!model.isReading && !model.isAttachmentRendered) #expect(!model.markAttachmentRendered(id: "file_1", previewID: oldPreviewID)) model.reportAttachmentFailure(id: "file_1", previewID: oldPreviewID, message: "迟到错误") #expect(model.attachmentErrorMessage == nil) await model.startReading(at: 100) #expect(await source.startReadingRequests.count == 1) let previewID = try #require(model.attachmentPreviewID) #expect(model.markAttachmentRendered(id: "file_2", previewID: previewID)) await model.startReading(at: 200) await model.recordVisibleTime(at: 201) #expect(model.activeSecondsTotal == 1) #expect(await source.startReadingRequests.count == 2) #expect(model.progress?.readingSeconds == 3) } /// 不能显示服务端错误返回的另一份附件,即使地址本身和有效期合法。 @Test("附件授权响应必须匹配所选附件标识") func mismatchedAttachmentAuthorizationIsRejected() async { let source = source() await source.configure { $0.attachmentURLHandler = { _ in TrainingAttachmentLink(id: "other-file", name: "另一份文档.txt", url: URL(string: "https://example.test/other.txt")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(60)) } } let model = model(source) await model.load() #expect(model.currentAttachmentID == "file_1") #expect(model.currentAttachmentLink == nil) #expect(model.attachmentErrorMessage != nil) await model.startReading(at: 0) #expect(await source.startReadingRequests.isEmpty) } /// 两种网页协议都能打开,带签名的查询参数不在客户端改写。 @Test("HTTP 和 HTTPS 附件原样返回有效签名地址", arguments: ["http", "https", "HTTP", "HTTPS"]) func attachmentAcceptsWebSchemes(_ scheme: String) async throws { let url = try #require(URL(string: "\(scheme)://example.test/training.pdf?Expires=1800003600&Signature=a%2Bb%3D")) let source = source(seconds: 20) await source.configure { $0.attachmentURLHandler = { id in TrainingAttachmentLink(id: id, name: "培训.pdf", url: url, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(60)) } } let model = model(source) await model.load() let link = await model.authorizeAttachment(id: "file_1") #expect(link?.url.absoluteString == url.absoluteString) #expect(model.errorMessage == nil) } /// 放行 HTTP 不能绕过服务端签名链接的有效期。 @Test("HTTP 和 HTTPS 附件到期或已过期时仍拒绝打开", arguments: ["http", "https"]) func expiredAttachmentIsRejected(_ scheme: String) async throws { let url = try #require(URL(string: "\(scheme)://example.test/training.pdf")) let source = source(seconds: 20) let model = model(source) await model.load() for offset: TimeInterval in [0, -1] { await source.configure { $0.attachmentURLHandler = { id in TrainingAttachmentLink(id: id, name: "培训.pdf", url: url, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(offset)) } } #expect(await model.authorizeAttachment(id: "file_1") == nil) #expect(model.errorMessage == "附件访问地址无效或已过期,请重试") } } /// 非网页协议、空主机和 URL 内嵌账号均不交给浏览器。 @Test("附件拒绝非网页协议和无效身份地址", arguments: [ "file:///private/training.pdf", "content://app/file", "javascript:alert(1)", "intent://app/file", "http:///file", "http://user:password@example.test/file", "https://user@example.test/file", ]) func invalidAttachmentIsRejected(_ value: String) async throws { let url = try #require(URL(string: value)) let source = source(seconds: 20) await source.configure { $0.attachmentURLHandler = { id in TrainingAttachmentLink(id: id, name: "培训.pdf", url: url, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(60)) } } let model = model(source) await model.load() #expect(await model.authorizeAttachment(id: "file_1") == nil) #expect(model.errorMessage == "附件访问地址无效或已过期,请重试") } /// 只读回顾仍能加载正文,但不创建会话、不增加读时。 @Test("已读完的只读课程不新建学习会话") func readOnlyDoesNotStartSession() async { let source = source(seconds: 20) let model = model(source) await loadRendered(model) await model.startReading(at: 0) await model.recordVisibleTime(at: 1000) #expect(model.currentAttachmentLink != nil) #expect(await source.startReadingRequests.isEmpty) #expect(await source.heartbeats.isEmpty) #expect(!model.isReading) } } /// 只模拟创建与心跳的服务器确认,支持先持久确认再丢响应和稳定业务失败。 private actor TrainingReadingReplyController { private var seconds = 0 private var sessions: [String: TrainingStudySession] = [:] private var bases: [String: Int] = [:] private var confirmations: [String: (TrainingDataStub.HeartbeatCall, TrainingHeartbeatConfirmation)] = [:] private var loseCreateResponse: Bool private var loseHeartbeatResponse: Bool private var nextFailure: TrainingRemoteError? /// 每个测试独立配置一次响应丢失或一次稳定业务错误。 init(loseCreateResponse: Bool = false, loseHeartbeatResponse: Bool = false, nextFailure: TrainingRemoteError? = nil) { self.loseCreateResponse = loseCreateResponse self.loseHeartbeatResponse = loseHeartbeatResponse self.nextFailure = nextFailure } /// 当前权威读时由服务端状态生成。 func progress() -> TrainingProgressSnapshot { TrainingRemoteFixtures.progress(seconds: seconds) } /// 同创建键返回原会话;响应丢失不撤销已经创建的会话。 func create(requestID: String) throws -> TrainingStudySession { if let saved = sessions[requestID] { return saved } let session = TrainingStudySession(sessionID: requestID, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600), heartbeatIntervalSeconds: 5, maxHeartbeatGapSeconds: 15, progress: progress()) sessions[requestID] = session bases[requestID] = seconds if loseCreateResponse { loseCreateResponse = false; throw URLError(.timedOut) } return session } /// 先记服务端确认,再抛超时;重试必须保留完整的原负载。 func confirm(_ call: TrainingDataStub.HeartbeatCall) throws -> TrainingHeartbeatConfirmation { if let failure = nextFailure { nextFailure = nil; throw failure } let key = "\(call.sessionID):\(call.sequence)" if let (prior, saved) = confirmations[key] { guard prior == call else { throw TrainingRemoteError.sessionConflict("changed retry payload") } return saved } seconds = min(20, max(seconds, (bases[call.sessionID] ?? 0) + call.activeSecondsTotal)) let result = TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence, acceptedActiveSecondsTotal: call.activeSecondsTotal, sessionClosed: call.final, progress: progress()) confirmations[key] = (call, result) if loseHeartbeatResponse { loseHeartbeatResponse = false; throw URLError(.timedOut) } return result } } /// 不使用固定延时的附件授权响应闸门,控制身份切换和迟到响应顺序。 private actor TrainingReadingAttachmentGate { private var response: CheckedContinuation? private var waiters: [CheckedContinuation] = [] /// 等待测试释放短链,通知测试请求已挂起。 func link() async -> TrainingAttachmentLink { await withCheckedContinuation { response = $0 waiters.forEach { $0.resume() } waiters = [] } } /// 等待授权请求已经挂起。 func waitUntilRequested() async { if response != nil { return } await withCheckedContinuation { waiters.append($0) } } /// 在身份变化后返回旧任务附件地址。 func release() { response?.resume(returning: TrainingAttachmentLink(id: "file_1", name: "旧文档.txt", url: URL(string: "https://example.test/training.txt")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))) response = nil } } /// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。 private actor TrainingReadingHeartbeatGate { private var response: CheckedContinuation? private var waiters: [CheckedContinuation] = [] private var hasDelayed = false /// 首个请求等待测试释放,后续最终心跳立即确认。 func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation { if !hasDelayed { hasDelayed = true await withCheckedContinuation { response = $0 waiters.forEach { $0.resume() } waiters = [] } } return TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence, acceptedActiveSecondsTotal: call.activeSecondsTotal, sessionClosed: call.final, progress: TrainingRemoteFixtures.progress(seconds: call.activeSecondsTotal)) } /// 不使用时间延迟,等待首个网络请求已经挂起。 func waitUntilRequested() async { if response != nil { return } await withCheckedContinuation { waiters.append($0) } } /// 让普通心跳完成,页面随后应使用新序号发送 final。 func release() { response?.resume(); response = nil } } /// 记录恢复动作是否已进入和完成,避免用固定延时验证串行等待。 @MainActor private final class TrainingReadingResumeProbe { var started = false var finished = false }