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) } } } /// 百节课程首次只读一页目录和一节正文,明确选择过的正文才缓存。 @Test("首次不遍历百节正文,目录主动分页,正文按选择复用") func lazyCourseResources() async { let source = source() await source.configure { $0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) } $0.sectionsHandler = { cursor in let range = cursor == nil ? 1...20 : 21...40 return TrainingCursorPage(items: range.map { TrainingSectionInfo(id: "s\($0)", order: $0, title: "小节\($0)") }, nextCursor: cursor == nil ? "next" : "last", hasMore: true, serverTime: nil) } } let model = model(source) await model.load() var calls = await source.calls #expect(model.sections.count == 20) #expect(calls.filter { $0.name == "sections" }.count == 1) #expect(calls.first { $0.name == "sections" }?.limit == 20) #expect(calls.filter { $0.name == "section" }.count == 1) #expect(!calls.contains { ["attachments", "paper", "questions", "draft", "attempts"].contains($0.name) }) await model.loadMoreSections() #expect(model.sections.count == 40) await model.selectSection(id: "s2") await model.selectSection(id: "s1") calls = await source.calls #expect(calls.filter { $0.name == "section" }.count == 2) #expect(calls.filter { $0.name == "sections" }.last?.cursor == "next") } /// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。 @Test("每五秒上报且门槛由后端确认,完成后停止会话") func batchedHeartbeatAndCompletion() async { let source = source() let model = model(source) await model.load() 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 model.load() 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 model.load() 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 model.load() 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 model.load() 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 model.load() 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 model.load() 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 model.load() 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 model.load() 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.currentSection != 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 model.load() 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.currentSection == nil) #expect(model.progress == nil) #expect(model.sections.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 model.load() 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 identityChangeDiscardsLateBody() async { let source = source() let gate = TrainingReadingBodyGate() await source.configure { $0.sectionHandler = { _ in await gate.body() } } 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.currentSection == nil) #expect(model.progress == nil) #expect(model.sections.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" let item = TrainingAttachmentInfo(id: id, name: "培训.pdf", mimeType: "application/pdf", sizeBytes: 1024, fileID: id, downloadURL: nil, expiresAt: nil) return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil) } } let model = model(source) await model.load() #expect(!(await source.calls).contains { $0.name == "attachments" }) await model.loadAttachments() await model.loadAttachments() #expect((await source.calls).filter { $0.name == "attachments" }.count == 1) #expect(!(await source.calls).contains { $0.name == "attachmentURL" }) await model.loadAttachments(loadMore: true) #expect(model.attachments.count == 2) let link = await model.authorizeAttachment(id: "file_1") #expect(link?.url.scheme == "https") #expect(link?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600)) #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1) } /// 两种网页协议都能打开,带签名的查询参数不在客户端改写。 @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 model.load() await model.startReading(at: 0) await model.recordVisibleTime(at: 1000) #expect(model.currentSection != 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 TrainingReadingBodyGate { private var response: CheckedContinuation? private var waiters: [CheckedContinuation] = [] /// 等待测试明确释放正文,通知等待请求已发出的测试代码。 func body() async -> TrainingSectionContent { 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: TrainingSectionContent(id: "s1", order: 1, title: "旧正文", contentHTML: "

旧账号课程

")) 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 }