feat(training): 接入真实培训接口与学习答题恢复

This commit is contained in:
2026-10-14 16:18:48 +08:00
parent 8862ae5401
commit 01068bb24e
28 changed files with 4945 additions and 238 deletions
+107
View File
@@ -40,6 +40,45 @@ final class APIClientTests: XCTestCase {
XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "token"), "test-token-abc")
}
func testQueryPreservesOpaqueCursorWithPlusAndDoesNotEncodePercentTwice() async throws {
let responseData = try TestJSON.envelope(data: AppConfigResponse(enableRegister: false))
let session = MockURLSession(responses: [responseData])
let client = APIClient(environment: .testing, session: session)
let cursor = "base64+part/with=padding 中文"
let literalPercent = "%2B already encoded text"
let _: AppConfigResponse = try await client.send(APIRequest(
method: .get,
path: "/api/app/config",
queryItems: [
URLQueryItem(name: "cursor", value: cursor),
URLQueryItem(name: "literal", value: literalPercent),
]
))
let url = try XCTUnwrap(session.requests.first?.url)
let components = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false))
let encodedQuery = try XCTUnwrap(components.percentEncodedQuery)
XCTAssertFalse(encodedQuery.contains("+"))
XCTAssertTrue(encodedQuery.contains("base64%2Bpart"))
XCTAssertTrue(encodedQuery.contains("part/with%3Dpadding"), "保留原有斜线编码语义,等号仍作为值编码")
XCTAssertTrue(encodedQuery.contains("%20"))
XCTAssertTrue(encodedQuery.contains("%E4%B8%AD%E6%96%87"))
XCTAssertTrue(encodedQuery.contains("literal=%252B%20"), "请求值中的字面百分号只编码一次")
XCTAssertFalse(encodedQuery.contains("base64%252B"), "修正生成的 %2B 不能再次编码为 %252B")
// 模拟 PHP/Laravel 常见的 form-query 解析,区别于 URLComponents 对 + 的保留行为。
let decodedPairs = encodedQuery.split(separator: "&").map { pair -> (String, String) in
let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
let name = String(parts[0]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? ""
let value = String(parts[1]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? ""
return (name, value)
}
let decoded = Dictionary(uniqueKeysWithValues: decodedPairs)
XCTAssertEqual(decoded["cursor"], cursor, "加号、空格、斜线、等号和中文均须原样到达后端")
XCTAssertEqual(decoded["literal"], literalPercent)
}
func testSendThrowsServerCodeErrorForBusinessFailure() async throws {
let responseData = try TestJSON.errorEnvelope(code: 100001, msg: "密码错误")
let session = MockURLSession(responses: [responseData])
@@ -97,6 +136,49 @@ final class APIClientTests: XCTestCase {
await fulfillment(of: [expectation], timeout: 1)
}
func testExpiredResponseFromReplacedTokenDoesNotExpireNewSession() async throws {
let center = NotificationCenter()
let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center)
expired.isInverted = true
let token = APIClientTestTokenState("old-token")
let session = APIClientExpiredResponseSession(
response: try TestJSON.errorEnvelope(code: 100060, msg: "旧 Token 已失效"),
beforeResponse: { token.value = "new-token" }
)
let client = APIClient(environment: .testing, session: session, notificationCenter: center)
client.bindAuthTokenProvider { token.value }
do {
let _: AppConfigResponse = try await client.send(APIRequest(method: .get, path: "/api/app/config"))
XCTFail("旧请求仍须向调用者返回原始失败")
} catch let APIError.serverCode(code, _) {
XCTAssertEqual(code, 100060)
}
let sentToken = await session.requestToken
XCTAssertEqual(sentToken, "old-token")
XCTAssertEqual(token.value, "new-token")
await fulfillment(of: [expired], timeout: 0.1)
}
func testExpiredResponseForCurrentTokenStillExpiresSession() async throws {
let center = NotificationCenter()
let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center)
let token = APIClientTestTokenState("current-token")
let session = APIClientExpiredResponseSession(
response: try TestJSON.errorEnvelope(code: 180024, msg: "Token 已失效"),
beforeResponse: { token.value = "current-token" }
)
let client = APIClient(environment: .testing, session: session, notificationCenter: center)
client.bindAuthTokenProvider { token.value }
_ = try? await client.send(APIRequest<AppConfigResponse>(method: .get, path: "/api/app/config"))
let sentToken = await session.requestToken
XCTAssertEqual(sentToken, "current-token")
await fulfillment(of: [expired], timeout: 1)
}
func testMultipartUploadBuildsAndroidCompatibleRequest() async throws {
let session = MockURLSession(responses: [try TestJSON.envelope(data: EmptyPayload())])
let client = APIClient(
@@ -152,3 +234,28 @@ final class APIClientTests: XCTestCase {
}
}
}
/// 网络等待期间可以切换的主 Actor 凭证,避免并发测试修改捕获变量。
@MainActor
private final class APIClientTestTokenState {
var value: String
init(_ value: String) { self.value = value }
}
/// 在请求已发出、响应返回前切换会话,模拟真实账号切换时的迟到失败。
private actor APIClientExpiredResponseSession: URLSessionProtocol {
private let response: Data
private let beforeResponse: @MainActor @Sendable () -> Void
private(set) var requestToken: String?
init(response: Data, beforeResponse: @escaping @MainActor @Sendable () -> Void) {
self.response = response
self.beforeResponse = beforeResponse
}
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
requestToken = request.value(forHTTPHeaderField: "token")
await beforeResponse()
return (response, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
}
+17 -5
View File
@@ -83,7 +83,7 @@ final class HomeViewModelTests: XCTestCase {
])
let viewModel = HomeViewModel(appStore: appStore)
viewModel.rebuildCommonMenus()
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
}
func testRebuildCommonMenusPersistsDefaultURIsOnFirstLoad() {
@@ -100,7 +100,7 @@ final class HomeViewModelTests: XCTestCase {
viewModel.rebuildCommonMenus()
XCTAssertEqual(viewModel.commonMenus.map(\.uri), [
"wallet", "cloud_management", "task_management", "system_settings", "/training",
"wallet", "cloud_management", "task_management", "system_settings",
])
XCTAssertEqual(
menuStore.savedCommonURIs(
@@ -120,7 +120,7 @@ final class HomeViewModelTests: XCTestCase {
await viewModel.loadPermissions(api: api, force: true)
XCTAssertTrue(viewModel.showPermissionDialog)
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["/training"])
XCTAssertTrue(viewModel.commonMenus.isEmpty)
}
func testPermissionApplyDestinationRoutesReviewingAndRejectedToStatus() async throws {
@@ -200,7 +200,7 @@ final class HomeViewModelTests: XCTestCase {
XCTAssertFalse(viewModel.showPermissionDialog)
XCTAssertTrue(viewModel.isMinimalTopRole)
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management", "/training"])
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management"])
XCTAssertEqual(viewModel.storeItem?.name, "测试门店")
}
@@ -227,10 +227,22 @@ final class HomeViewModelTests: XCTestCase {
viewModel.markNeedsPermissionReload()
await viewModel.reloadIfNeeded(api: api)
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
XCTAssertEqual(session.requests.count, 1)
}
/// 培训入口仅向店铺账号开放,权限菜单不能绕过账号类型限制。
func testTrainingEntryIsStoreOnlyAndDoesNotDuplicatePermissionMenu() {
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
let viewModel = HomeViewModel(appStore: appStore)
viewModel.rebuildCommonMenus()
XCTAssertFalse(viewModel.commonMenus.contains { $0.uri == "/training" })
appStore.session.accountType = .storeUser
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
viewModel.rebuildCommonMenus()
XCTAssertEqual(viewModel.commonMenus.filter { $0.uri == "/training" }.count, 1)
}
func testUnreadMessageStatusUsesCountEndpointAndUpdatesBadgeState() async {
let api = HomeMessageCenterAPIMock()
api.unreadCountResponses = [
+261
View File
@@ -0,0 +1,261 @@
import Foundation
import XCTest
@testable import suixinkan
/// 正式培训契约测试:校验独立资源、请求体、日期、稳定错误及身份边界。
@MainActor
final class TrainingAPITests: XCTestCase {
private let dateText = "2026-10-14T10:00:00+08:00"
func testSummaryTaskPageAndFlatDetailDecodeServerTypes() async throws {
var detail = taskJSON
detail.merge(["required_reading_seconds": 20, "reading_rule": "course_duration", "scoring": NSNull(), "server_time": dateText]) { _, new in new }
let session = MockURLSession(responses: [
try envelope(["pending_count": 7, "completed_count": 12, "latest_attempt": NSNull(), "server_time": dateText]),
try envelope(["items": [taskJSON], "next_cursor": NSNull(), "has_more": false, "server_time": dateText]),
try envelope(detail),
try envelope(["items": [], "next_cursor": NSNull(), "has_more": false, "server_time": dateText]),
])
let client = APIClient(environment: .testing, session: session)
client.bindAuthTokenProvider { "current-token" }
let api = TrainingAPI(client: client)
let summary = try await api.summary()
let page = try await api.tasks(status: .pendingExam, keyword: "游客 服务", cursor: nil, limit: 3)
let task = try await api.task(id: "task_101")
let empty = try await api.tasks(status: nil, keyword: "", cursor: "cursor+opaque", limit: 80)
XCTAssertEqual(summary.pendingCount, 7)
XCTAssertNil(summary.latestAttempt)
XCTAssertEqual(page.items.first?.learnerStatus, .pendingExam)
XCTAssertNil(page.items.first?.startAt)
XCTAssertNil(page.items.first?.endAt)
XCTAssertNil(page.items.first?.paperSnapshotID)
XCTAssertNil(page.items.first?.passScore)
XCTAssertEqual(task.summary.id, "task_101")
XCTAssertEqual(task.requiredReadingSeconds, 20)
XCTAssertEqual(task.readingRule, "course_duration")
XCTAssertEqual(task.serverTime, try XCTUnwrap(ISO8601DateFormatter().date(from: dateText)))
XCTAssertTrue(empty.items.isEmpty)
XCTAssertNil(empty.nextCursor)
XCTAssertEqual(try query(session.requests[1]), ["learner_status": "pending", "keyword": "游客 服务", "limit": "3"])
XCTAssertEqual(try query(session.requests[3]), ["cursor": "cursor+opaque", "limit": "50"])
XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "token"), "current-token")
XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "X-OS-TYPE"), "iOS")
}
func testCourseResourcesCarryTaskAuthorizationAndDoNotAggregate() async throws {
let session = MockURLSession(responses: [
try envelope(["course_snapshot_id": "cs_3", "title": "规范", "introduction": "简介", "section_count": 1, "attachment_count": 1]),
try envelope(["items": [["section_id": "section_1", "order": 1, "title": "正文"]], "next_cursor": NSNull(), "has_more": false]),
try envelope(["section_id": "section_1", "order": 1, "title": "正文", "content_html": "<p>正式内容</p>"]),
try envelope(["items": [["attachment_id": "file_1", "name": "规范.pdf", "mime_type": "application/pdf", "size_bytes": 4096, "file_id": "file_1", "download_url": NSNull(), "expires_at": NSNull()]], "next_cursor": NSNull(), "has_more": false]),
try envelope(["attachment_id": "file_1", "name": "规范.pdf", "url": "https://files.zhifly.cn/private?signature=one", "expires_at": dateText]),
])
let api = TrainingAPI(client: APIClient(environment: .testing, session: session))
let course = try await api.course(id: "cs_3", taskID: "task_101")
let sections = try await api.sections(courseID: "cs_3", taskID: "task_101", cursor: nil, limit: 20)
let content = try await api.section(courseID: "cs_3", sectionID: "section_1", taskID: "task_101")
let attachments = try await api.attachments(courseID: "cs_3", taskID: "task_101", cursor: "attachment-cursor", limit: 20)
let link = try await api.attachmentURL(courseID: "cs_3", attachmentID: "file_1", taskID: "task_101")
XCTAssertEqual(course.id, "cs_3")
XCTAssertEqual(sections.items.first?.id, "section_1")
XCTAssertEqual(content.contentHTML, "<p>正式内容</p>")
XCTAssertNil(attachments.items.first?.downloadURL)
XCTAssertEqual(link.url.host, "files.zhifly.cn")
XCTAssertEqual(session.requests.count, 5)
for request in session.requests {
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertEqual(try query(request)["task_id"], "task_101")
}
XCTAssertEqual(session.requests[2].url?.path, "/api/app/training/courses/cs_3/sections/section_1")
XCTAssertEqual(session.requests[4].url?.path, "/api/app/training/courses/cs_3/attachments/file_1")
XCTAssertEqual(try query(session.requests[3])["cursor"], "attachment-cursor")
}
func testReadingSessionAndHeartbeatKeepCallerIdempotencyData() async throws {
let session = MockURLSession(responses: [
try envelope(progressJSON),
try envelope(["session_id": "session-uuid", "expires_at": dateText, "heartbeat_interval_seconds": 5, "max_heartbeat_gap_seconds": 15, "progress": progressJSON]),
try envelope(["session_id": "session-uuid", "accepted_sequence": 1, "accepted_active_seconds_total": 5, "session_closed": true, "progress": progressJSON]),
])
let api = TrainingAPI(client: APIClient(environment: .testing, session: session))
let progress = try await api.progress(taskID: "task_101")
let reading = try await api.startReading(taskID: "task_101", requestID: "read-id")
let confirmation = try await api.heartbeat(sessionID: reading.sessionID, sequence: 1, activeSecondsTotal: 5, final: true)
XCTAssertEqual(progress.readingSeconds, 12)
XCTAssertEqual(reading.heartbeatIntervalSeconds, 5)
XCTAssertEqual(confirmation.acceptedSequence, 1)
XCTAssertEqual(confirmation.acceptedActiveSecondsTotal, 5)
XCTAssertTrue(confirmation.sessionClosed)
XCTAssertEqual(try body(session.requests[1])["request_id"] as? String, "read-id")
let heartbeat = try body(session.requests[2])
XCTAssertEqual(Set(heartbeat.keys), ["sequence", "active_seconds_total", "final"])
XCTAssertEqual(heartbeat["active_seconds_total"] as? Int, 5)
XCTAssertEqual(heartbeat["final"] as? Bool, true)
}
func testQuestionDraftAndPatchUseFrozenPositionsAndVersion() async throws {
let session = MockURLSession(responses: [
try envelope(["paper_snapshot_id": "ps_3", "scoring": "equal-percentage-v1", "question_count": 30, "max_options_per_question": 6]),
try envelope(["paper_snapshot_id": "ps_3", "total": 30, "offset": 10, "next_offset": 20, "has_more": true, "items": [questionJSON]]),
try envelope(draftJSON),
try envelope(["draft_revision": 5, "saved_at": dateText, "answered_count": 2]),
try envelope(["draft_revision": 8, "saved_at": dateText, "answered_count": 3]),
])
let api = TrainingAPI(client: APIClient(environment: .testing, session: session))
let paper = try await api.paper(id: "ps_3", taskID: "task_101")
let questions = try await api.questions(paperID: "ps_3", taskID: "task_101", offset: 10, limit: 10)
let draft = try await api.draft(taskID: "task_101", offset: 0, limit: 0)
let saved = try await api.saveDraft(taskID: "task_101", request: TrainingDraftSaveRequest(requestID: "save-id", paperSnapshotID: "ps_3", baseRevision: 4, lastQuestionOrder: 11, changes: [TrainingDraftChange(questionID: "101", selectedOptionIDs: ["A", "B"])]))
let reset = try await api.resetDraft(taskID: "task_101", request: TrainingDraftResetRequest(requestID: "reset-id", paperSnapshotID: "ps_3", baseRevision: 5))
XCTAssertEqual(paper.questionCount, 30)
XCTAssertEqual(questions.items.first?.id, "101")
XCTAssertEqual(questions.items.first?.options.map(\.id), ["A", "B"])
XCTAssertEqual(questions.offset, 10)
XCTAssertEqual(draft.answeredQuestionOrders, [1, 11])
XCTAssertNil(draft.savedAt)
XCTAssertEqual(try query(session.requests[2])["limit"], "0")
XCTAssertEqual(saved.draftRevision, 5)
XCTAssertEqual(reset.draftRevision, 8)
XCTAssertEqual(reset.answeredCount, 3, "重置重试可能返回已重新作答的实况,不能假定为零")
XCTAssertEqual(session.requests[3].httpMethod, "PATCH")
let patch = try body(session.requests[3])
XCTAssertEqual(patch["request_id"] as? String, "save-id")
XCTAssertEqual(patch["base_revision"] as? Int, 4)
let changes = try XCTUnwrap(patch["changes"] as? [[String: Any]])
XCTAssertEqual(changes.first?["selected_option_ids"] as? [String], ["A", "B"])
XCTAssertEqual(session.requests[4].url?.path, "/api/app/training/tasks/task_101/draft/reset")
}
func testSubmissionUsesOnlyDraftVersionAndResultRecoveryIsPrecise() async throws {
let taskState: [String: Any] = ["learner_status": "completed", "completed_at": dateText, "can_retry": false, "block_reason": "completed"]
var review = questionJSON
review.merge(["selected_option_ids": ["A"], "correct_option_ids": ["A"], "is_correct": true, "explanation": "说明服务规则"]) { _, new in new }
let session = MockURLSession(responses: [
try envelope(["attempt": attemptJSON, "task_state": taskState, "draft_revision": 6, "server_time": dateText]),
try envelope(["items": [attemptJSON], "next_cursor": NSNull(), "has_more": false]),
try envelope(["attempt": attemptJSON, "task_state": taskState, "server_time": dateText]),
try envelope(["attempt_id": "attempt_12", "items": [review], "next_cursor": NSNull(), "has_more": false]),
])
let api = TrainingAPI(client: APIClient(environment: .testing, session: session))
let result = try await api.submit(taskID: "task_101", request: TrainingSubmissionRequest(submissionID: "submit-id", paperSnapshotID: "ps_3", draftRevision: 5))
let recovered = try await api.attempts(taskID: "task_101", submissionID: "submit-id", cursor: nil, limit: 1)
let detail = try await api.attempt(id: "attempt_12")
let reviews = try await api.reviews(attemptID: "attempt_12", cursor: nil, limit: 50)
let submission = try body(session.requests[0])
XCTAssertEqual(Set(submission.keys), ["submission_id", "paper_snapshot_id", "draft_revision"])
XCTAssertNil(submission["answers"])
XCTAssertEqual(result.attempt.id, "attempt_12")
XCTAssertEqual(result.attempt.scoreText, "87.5")
XCTAssertEqual(result.draftRevision, 6)
XCTAssertEqual(recovered.items.first?.id, result.attempt.id)
XCTAssertEqual(try query(session.requests[1]), ["task_id": "task_101", "submission_id": "submit-id", "limit": "1"])
XCTAssertFalse(detail.taskState.canRetry)
XCTAssertEqual(reviews.items.first?.correctOptionIDs, ["A"])
XCTAssertEqual(try query(session.requests[3])["limit"], "10")
}
func testStableTrainingErrorsAreMappedWithoutSwallowingAuthenticationErrors() async throws {
let codes = Array(150100...150113)
let responses = try codes.map { try TestJSON.errorEnvelope(code: $0, msg: "业务错误") } + [try TestJSON.errorEnvelope(code: 100060, msg: "登录失效")]
let api = TrainingAPI(client: APIClient(environment: .testing, session: MockURLSession(responses: responses)))
for code in codes {
do { _ = try await api.summary(); XCTFail("应抛培训业务错误") }
catch let error as TrainingRemoteError {
XCTAssertEqual(error.code, code)
XCTAssertEqual(error.errorDescription, "业务错误")
}
}
do { _ = try await api.summary(); XCTFail("应保留登录失效错误") }
catch let APIError.serverCode(code, _) { XCTAssertEqual(code, 100060) }
}
func testInvalidAccountAndChangedIdentityNeverDeliverTrainingData() async throws {
let unused = MockURLSession(responses: [try envelope([:])])
let ineligible = TrainingAPI(client: APIClient(environment: .testing, session: unused), eligible: false)
do { _ = try await ineligible.summary(); XCTFail("应拒绝非店铺身份") }
catch let error as TrainingRemoteError { XCTAssertEqual(error.code, 150100) }
XCTAssertTrue(unused.requests.isEmpty)
let before = TrainingAPI(client: APIClient(environment: .testing, session: unused), validateContext: { false })
do { _ = try await before.summary(); XCTFail("请求前应校验身份") }
catch let error as TrainingRemoteError { XCTAssertEqual(error, .identityChanged) }
XCTAssertTrue(unused.requests.isEmpty)
let identity = TrainingAPITestIdentity()
let delayed = TrainingIdentityChangingSession(response: try envelope(["pending_count": 0, "completed_count": 0, "latest_attempt": NSNull(), "server_time": dateText]), change: { identity.isCurrent = false })
let after = TrainingAPI(client: APIClient(environment: .testing, session: delayed), tokenOverride: "frozen-token", validateContext: { identity.isCurrent })
do { _ = try await after.summary(); XCTFail("迟到响应不得返回给新身份") }
catch let error as TrainingRemoteError { XCTAssertEqual(error, .identityChanged) }
let token = await delayed.lastToken
XCTAssertEqual(token, "frozen-token")
}
func testRFC3339FractionalSecondsAndInvalidDatesStayLocalToTrainingDTOs() throws {
let decoder = JSONDecoder()
let json = #"{"attempt_id":"attempt_1","score_hundredths":9999,"submitted_at":"2026-10-14T10:00:00.123+08:00"}"#
let attempt = try decoder.decode(TrainingLatestAttempt.self, from: Data(json.utf8))
XCTAssertEqual(attempt.submittedAt.timeIntervalSince1970.truncatingRemainder(dividingBy: 1), 0.123, accuracy: 0.001)
let invalid = json.replacingOccurrences(of: "2026-10-14T10:00:00.123+08:00", with: "2026-10-14 10:00:00")
XCTAssertThrowsError(try decoder.decode(TrainingLatestAttempt.self, from: Data(invalid.utf8)))
}
private var flagsJSON: [String: Any] {
["progress_percent": 0, "reading_completed": false, "has_draft": false, "can_view_course": true, "can_study": true, "can_start_exam": false, "block_reason": "reading_required"]
}
private var taskJSON: [String: Any] {
["task_id": "task_101", "title": "规范培训", "publisher_name": NSNull(), "mode": "study", "task_status": "published", "learner_status": "pending", "start_at": NSNull(), "end_at": NSNull(), "course_snapshot_id": "cs_3", "course_title": "规范", "paper_snapshot_id": NSNull(), "section_count": 1, "question_count": 0, "pass_score": NSNull(), "learning": flagsJSON]
}
private var progressJSON: [String: Any] {
var fields = flagsJSON
fields.merge(["task_id": "task_101", "reading_seconds": 12, "required_reading_seconds": 20, "completed_section_count": 0, "section_count": 1, "learner_status": "pending", "completed_at": NSNull(), "can_retry": false, "server_time": dateText]) { _, new in new }
return fields
}
private var questionJSON: [String: Any] {
["question_id": "101", "order": 11, "type": "multiple", "stem": "请选择", "options": [["option_id": "A", "text": "说明规范"], ["option_id": "B", "text": "确认费用"]]]
}
private var draftJSON: [String: Any] {
["task_id": "task_101", "paper_snapshot_id": "ps_3", "draft_revision": 4, "saved_at": NSNull(), "last_question_order": 11, "answered_count": 2, "answered_question_orders": [1, 11], "total": 30, "offset": 0, "next_offset": NSNull(), "has_more": false, "items": []]
}
private var attemptJSON: [String: Any] {
["attempt_id": "attempt_12", "task_id": "task_101", "task_title": "规范培训", "course_snapshot_id": "cs_3", "course_title": "规范", "paper_snapshot_id": "ps_3", "submitted_at": dateText, "score_hundredths": 8750, "correct_count": 7, "question_count": 8, "pass_score": 80, "passed": true, "review_available": true]
}
private func envelope(_ payload: [String: Any]) throws -> Data {
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": payload])
}
private func body(_ request: URLRequest) throws -> [String: Any] {
try XCTUnwrap(JSONSerialization.jsonObject(with: try XCTUnwrap(request.httpBody)) as? [String: Any])
}
private func query(_ request: URLRequest) throws -> [String: String] {
let url = try XCTUnwrap(request.url)
return Dictionary(uniqueKeysWithValues: (URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []).compactMap { item in item.value.map { (item.name, $0) } })
}
}
/// 测试中可控的主 Actor 身份标记。
@MainActor
private final class TrainingAPITestIdentity {
var isCurrent = true
}
/// 在响应返回前切换身份,验证生产数据源丢弃迟到结果。
private actor TrainingIdentityChangingSession: URLSessionProtocol {
private let response: Data
private let change: @MainActor @Sendable () -> Void
private(set) var lastToken: String?
init(response: Data, change: @escaping @MainActor @Sendable () -> Void) {
self.response = response
self.change = change
}
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
lastToken = request.value(forHTTPHeaderField: "token")
await change()
return (response, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
}
@@ -0,0 +1,271 @@
import Foundation
@testable import suixinkan
/// 正式 DTO 测试样例,所有数据在内存中生成,不发出真实请求。
enum TrainingRemoteFixtures {
static let now = Date(timeIntervalSince1970: 1_800_000_000)
/// 固定试卷的一题。
static func question(_ order: Int) -> TrainingQuestionItem {
TrainingQuestionItem(id: "q\(order)", order: order, type: .single, stem: "培训题目 \(order)", options: [TrainingQuestionOption(id: "A", text: "正确选择"), TrainingQuestionOption(id: "B", text: "另一选择")])
}
/// 不含正文和答案的任务摘要。
static func task(id: String = "task_1", title: String = "一线服务规范学习", questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskSummary {
TrainingTaskSummary(id: id, title: title, publisherName: "培训负责人", mode: .exam, taskStatus: .published, learnerStatus: .pendingExam, startAt: nil, endAt: nil, courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", sectionCount: 2, questionCount: questionCount, passScore: 80, learning: TrainingLearningFlags(progressPercent: readingCompleted ? 100 : 0, readingCompleted: readingCompleted, hasDraft: false, canViewCourse: true, canStudy: !readingCompleted, canStartExam: readingCompleted, blockReason: readingCompleted ? nil : "reading_required"))
}
/// 轻量任务详情。
static func detail(questionCount: Int = 30, readingCompleted: Bool = true) -> TrainingTaskDetail {
TrainingTaskDetail(summary: task(questionCount: questionCount, readingCompleted: readingCompleted), requiredReadingSeconds: 20, readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: now)
}
/// 服务端确认读时与资格。
static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot {
TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now)
}
/// 单次已提交成绩。
static func attempt(id: String = "attempt_1", passed: Bool = true, questionCount: Int = 30, reviewAvailable: Bool = true) -> TrainingAttemptSummary {
TrainingAttemptSummary(id: id, taskID: "task_1", taskTitle: "一线服务规范学习", courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", submittedAt: now, scoreHundredths: passed ? 10000 : 5000, correctCount: passed ? questionCount : questionCount / 2, questionCount: questionCount, passScore: 80, passed: passed, reviewAvailable: reviewAvailable)
}
/// 冻结成绩的当前操作资格。
static func result(passed: Bool = true, reviewAvailable: Bool = true, questionCount: Int = 30) -> TrainingAttemptDetail {
TrainingAttemptDetail(attempt: attempt(passed: passed, questionCount: questionCount, reviewAvailable: reviewAvailable), taskState: TrainingTaskState(learnerStatus: passed ? .completed : .pendingExam, completedAt: passed ? now : nil, canRetry: !passed, blockReason: passed ? "completed" : nil), serverTime: now)
}
/// 一页解析。
static func review(_ order: Int = 1) -> TrainingReviewItem {
let question = question(order)
return TrainingReviewItem(id: question.id, order: order, type: question.type, stem: question.stem, options: question.options, selectedOptionIDs: ["A"], correctOptionIDs: ["A"], isCorrect: true, explanation: "应先向游客说明服务内容与费用。")
}
}
/// 通用培训替身,允许测试注入失败和丢响应,记录实际的轻量资源调用。
actor TrainingDataStub: TrainingDataServing {
/// 可核对分页、上报和资源范围的调用参数。
struct Call: Equatable, Sendable {
let name: String
var taskID: String? = nil
var cursor: String? = nil
var offset: Int? = nil
var limit: Int? = nil
}
/// 心跳的固定幂等负载。
struct HeartbeatCall: Equatable, Sendable {
let sessionID: String
let sequence: Int
let activeSecondsTotal: Int
let final: Bool
}
/// 各方法可替换响应,未替换的方法使用独立内存状态。
struct Configuration: Sendable {
var questionCount = 30
var readingSeconds = 20
var summaryHandler: (@Sendable () async throws -> TrainingSummary)?
var tasksHandler: (@Sendable (TrainingLearnerStatus?, String, String?, Int) async throws -> TrainingCursorPage<TrainingTaskSummary>)?
var taskHandler: (@Sendable (String) async throws -> TrainingTaskDetail)?
var progressHandler: (@Sendable (String) async throws -> TrainingProgressSnapshot)?
var courseHandler: (@Sendable () async throws -> TrainingCourseInfo)?
var sectionsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingSectionInfo>)?
var sectionHandler: (@Sendable (String) async throws -> TrainingSectionContent)?
var attachmentsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingAttachmentInfo>)?
var startReadingHandler: (@Sendable (String) async throws -> TrainingStudySession)?
var heartbeatHandler: (@Sendable (HeartbeatCall) async throws -> TrainingHeartbeatConfirmation)?
var questionsHandler: (@Sendable (Int, Int) async throws -> TrainingQuestionPage)?
var draftHandler: (@Sendable (Int, Int) async throws -> TrainingDraftPage)?
var saveHandler: (@Sendable (TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation)?
var resetHandler: (@Sendable (TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation)?
var submitHandler: (@Sendable (TrainingSubmissionRequest) async throws -> TrainingSubmissionResult)?
var attemptsHandler: (@Sendable (String?, String?, String?) async throws -> TrainingCursorPage<TrainingAttemptSummary>)?
var attemptHandler: (@Sendable (String) async throws -> TrainingAttemptDetail)?
var reviewsHandler: (@Sendable (String?) async throws -> TrainingReviewPage)?
}
private var configuration: Configuration
private(set) var calls: [Call] = []
private(set) var savedRequests: [TrainingDraftSaveRequest] = []
private(set) var resetRequests: [TrainingDraftResetRequest] = []
private(set) var submissionRequests: [TrainingSubmissionRequest] = []
private(set) var heartbeats: [HeartbeatCall] = []
private(set) var startReadingRequests: [String] = []
private var revision = 1
private var answers: [String: [String]] = [:]
private var lastOrder = 0
private var submitted: [String: TrainingSubmissionResult] = [:]
private var savedPayloads: [String: TrainingDraftSaveRequest] = [:]
private var resetPayloads: [String: TrainingDraftResetRequest] = [:]
private var submissionPayloads: [String: TrainingSubmissionRequest] = [:]
private var readingBases: [String: Int] = [:]
private var heartbeatConfirmations: [String: TrainingHeartbeatConfirmation] = [:]
private var heartbeatPayloads: [String: HeartbeatCall] = [:]
private var savedConfirmations: [String: TrainingDraftConfirmation] = [:]
private var readingSeconds: Int
/// 每个测试独立初始化,默认不复用其他测试状态。
init(configuration: Configuration = Configuration()) {
self.configuration = configuration
readingSeconds = configuration.readingSeconds
}
/// 在 actor 内更换响应配置。
func configure(_ update: @Sendable (inout Configuration) -> Void) { update(&configuration) }
/// 注入一个已有草稿,供跨设备和恢复测试。
func seedDraft(revision: Int, answers: [String: [String]], lastOrder: Int = 0) {
self.revision = revision; self.answers = answers; self.lastOrder = lastOrder
}
/// 读取概览,不派生全量任务历史。
func summary() async throws -> TrainingSummary {
calls.append(Call(name: "summary"))
if let handler = configuration.summaryHandler { return try await handler() }
return TrainingSummary(pendingCount: 1, completedCount: 0, latestAttempt: nil, serverTime: TrainingRemoteFixtures.now)
}
/// 记录任务过滤及游标。
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary> {
calls.append(Call(name: "tasks", cursor: cursor, limit: limit))
if let handler = configuration.tasksHandler { return try await handler(status, keyword, cursor, limit) }
return TrainingCursorPage(items: [TrainingRemoteFixtures.task(questionCount: configuration.questionCount)], nextCursor: nil, hasMore: false, serverTime: TrainingRemoteFixtures.now)
}
/// 任务详情仍不携带正文或试卷。
func task(id: String) async throws -> TrainingTaskDetail {
calls.append(Call(name: "task", taskID: id))
if let handler = configuration.taskHandler { return try await handler(id) }
return TrainingRemoteFixtures.detail(questionCount: configuration.questionCount, readingCompleted: readingSeconds >= 20)
}
/// 课程元信息。
func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
calls.append(Call(name: "course", taskID: taskID))
if let handler = configuration.courseHandler { return try await handler() }
return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 0)
}
/// 小节目录,仅含标题与序号。
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
calls.append(Call(name: "sections", taskID: taskID, cursor: cursor, limit: limit))
if let handler = configuration.sectionsHandler { return try await handler(cursor) }
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s1", order: 1, title: "接待礼仪"), TrainingSectionInfo(id: "s2", order: 2, title: "问题处理")], nextCursor: nil, hasMore: false, serverTime: nil)
}
/// 仅请求指定小节正文。
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent {
calls.append(Call(name: "section", taskID: taskID))
if let handler = configuration.sectionHandler { return try await handler(sectionID) }
return TrainingSectionContent(id: sectionID, order: sectionID == "s1" ? 1 : 2, title: "接待礼仪", contentHTML: "<p>主动问候,并清晰说明服务内容。</p>")
}
/// 分页附件元数据。
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
calls.append(Call(name: "attachments", taskID: taskID, cursor: cursor, limit: limit))
if let handler = configuration.attachmentsHandler { return try await handler(cursor) }
return TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil)
}
/// 返回用于 Safari 的授权 HTTPS URL。
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
calls.append(Call(name: "attachmentURL", taskID: taskID))
return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
}
/// 只返回权威读时。
func progress(taskID: String) async throws -> TrainingProgressSnapshot {
calls.append(Call(name: "progress", taskID: taskID))
if let handler = configuration.progressHandler { return try await handler(taskID) }
return TrainingRemoteFixtures.progress(seconds: readingSeconds)
}
/// 创建会话,记录幂等键。
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession {
calls.append(Call(name: "startReading", taskID: taskID)); startReadingRequests.append(requestID)
if let handler = configuration.startReadingHandler { return try await handler(requestID) }
if readingBases[requestID] == nil { readingBases[requestID] = readingSeconds }
return TrainingStudySession(sessionID: requestID, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600), heartbeatIntervalSeconds: 5, maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: readingSeconds))
}
/// 测试按序号返回确认,不接触真实学员记录。
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation {
let call = HeartbeatCall(sessionID: sessionID, sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final)
heartbeats.append(call); calls.append(Call(name: "heartbeat"))
if let handler = configuration.heartbeatHandler { return try await handler(call) }
let key = "\(sessionID):\(sequence)"
if let prior = heartbeatConfirmations[key] {
guard heartbeatPayloads[key] == call else { throw TrainingRemoteError.sessionConflict("序号冲突") }
return prior
}
readingSeconds = min(20, max(readingSeconds, (readingBases[sessionID] ?? 0) + activeSecondsTotal))
let result = TrainingHeartbeatConfirmation(sessionID: sessionID, acceptedSequence: sequence, acceptedActiveSecondsTotal: activeSecondsTotal, sessionClosed: final, progress: TrainingRemoteFixtures.progress(seconds: readingSeconds))
heartbeatConfirmations[key] = result; heartbeatPayloads[key] = call
return result
}
/// 不含题目数组的试卷元信息。
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo {
calls.append(Call(name: "paper", taskID: taskID))
return TrainingPaperInfo(id: id, scoring: "equal-percentage-v1", questionCount: configuration.questionCount, maxOptionsPerQuestion: 6)
}
/// 仅生成请求范围内的固定题位。
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage {
calls.append(Call(name: "questions", taskID: taskID, offset: offset, limit: limit))
if let handler = configuration.questionsHandler { return try await handler(offset, limit) }
let end = min(configuration.questionCount, offset + limit)
let items = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
return TrainingQuestionPage(paperSnapshotID: paperID, total: configuration.questionCount, offset: offset, nextOffset: end < configuration.questionCount ? end : nil, hasMore: end < configuration.questionCount, items: items)
}
/// 草稿元信息覆盖全卷,答案仅提供当前范围。
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage {
calls.append(Call(name: "draft", taskID: taskID, offset: offset, limit: limit))
if let handler = configuration.draftHandler { return try await handler(offset, limit) }
let orders = answers.filter { !$0.value.isEmpty }.keys.compactMap { Int($0.dropFirst()) }.sorted()
let end = min(configuration.questionCount, offset + limit)
let items = limit > 0 ? orders.filter { $0 > offset && $0 <= end }.map { TrainingDraftAnswerItem(questionID: "q\($0)", order: $0, selectedOptionIDs: answers["q\($0)"] ?? []) } : []
return TrainingDraftPage(taskID: taskID, paperSnapshotID: "paper_1", draftRevision: revision, savedAt: answers.isEmpty ? nil : TrainingRemoteFixtures.now, lastQuestionOrder: lastOrder, answeredCount: orders.count, answeredQuestionOrders: orders, total: configuration.questionCount, offset: offset, nextOffset: limit > 0 && end < configuration.questionCount ? end : nil, hasMore: limit > 0 && end < configuration.questionCount, items: items)
}
/// 默认实现模拟版本比较与单题替换。
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation {
savedRequests.append(request); calls.append(Call(name: "saveDraft", taskID: taskID))
if let handler = configuration.saveHandler { return try await handler(request) }
if let confirmation = savedConfirmations[request.requestID] {
guard savedPayloads[request.requestID] == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") }
return confirmation
}
guard request.baseRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") }
for change in request.changes { answers[change.questionID] = change.selectedOptionIDs }
if let order = request.lastQuestionOrder { lastOrder = order }
if !request.changes.isEmpty { revision += 1 }
let result = TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: answers.values.filter { !$0.isEmpty }.count)
savedConfirmations[request.requestID] = result
savedPayloads[request.requestID] = request
return result
}
/// 重置确认可由测试返回非空当前实况。
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation {
resetRequests.append(request); calls.append(Call(name: "resetDraft", taskID: taskID))
if let handler = configuration.resetHandler { return try await handler(request) }
if let prior = resetPayloads[request.requestID] {
guard prior == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") }
return TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: answers.values.filter { !$0.isEmpty }.count)
}
guard request.baseRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") }
resetPayloads[request.requestID] = request
answers = [:]; revision += 1; lastOrder = 0
return TrainingDraftConfirmation(draftRevision: revision, savedAt: TrainingRemoteFixtures.now, answeredCount: 0)
}
/// 默认交卷只消费已经保存的版本。
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult {
submissionRequests.append(request); calls.append(Call(name: "submit", taskID: taskID))
if let handler = configuration.submitHandler { return try await handler(request) }
if let result = submitted[request.submissionID] {
guard submissionPayloads[request.submissionID] == request else { throw TrainingRemoteError.idempotencyConflict("幂等键冲突") }
return result
}
guard request.draftRevision == revision else { throw TrainingRemoteError.draftRevisionConflict("版本冲突") }
guard answers.values.filter({ !$0.isEmpty }).count == configuration.questionCount else { throw TrainingRemoteError.answerIncomplete("存在未答题") }
let detail = TrainingRemoteFixtures.result(questionCount: configuration.questionCount)
revision += 1; answers = [:]
let result = TrainingSubmissionResult(attempt: detail.attempt, taskState: detail.taskState, draftRevision: revision, serverTime: TrainingRemoteFixtures.now)
submitted[request.submissionID] = result
submissionPayloads[request.submissionID] = request
return result
}
/// 记录列表或提交恢复只返回摘要。
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary> {
calls.append(Call(name: "attempts", taskID: taskID, cursor: cursor, limit: limit))
if let handler = configuration.attemptsHandler { return try await handler(taskID, submissionID, cursor) }
return TrainingCursorPage(items: submissionID.flatMap { submitted[$0]?.attempt }.map { [$0] } ?? [], nextCursor: nil, hasMore: false, serverTime: nil)
}
/// 成绩首屏没有解析数组。
func attempt(id: String) async throws -> TrainingAttemptDetail {
calls.append(Call(name: "attempt"))
if let handler = configuration.attemptHandler { return try await handler(id) }
return TrainingRemoteFixtures.result(questionCount: configuration.questionCount)
}
/// 展开解析时才记录调用。
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage {
calls.append(Call(name: "reviews", cursor: cursor, limit: limit))
if let handler = configuration.reviewsHandler { return try await handler(cursor) }
return TrainingReviewPage(attemptID: attemptID, items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false)
}
}
+11 -9
View File
@@ -368,20 +368,22 @@ struct TrainingFeatureTests {
#expect(model.errorMessage != nil)
}
@Test("首页所有角色都有培训入口,服务端下发时不重复")
func trainingEntryForEveryRole() {
@Test("培训入口按店铺账号开放,权限下发不重复且不能绕过账号限制")
func trainingEntryFollowsAccountScope() {
let suite = "TrainingMenuTests-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: suite) else { Issue.record("无法创建独立存储"); return }
defer { defaults.removePersistentDomain(forName: suite) }
let appStore = AppStore(defaults: defaults)
appStore.session.userId = "1001"
appStore.session.accountType = .scenicUser
for role in AppRoleCode.allCases {
appStore.session.roleCode = role.rawValue
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults))
model.rebuildCommonMenus()
#expect(model.commonMenus.filter { $0.uri == "/training" }.count == 1)
for accountType in [AppAccountType.scenicUser, .storeUser] {
appStore.session.accountType = accountType
for role in AppRoleCode.allCases {
appStore.session.roleCode = role.rawValue
appStore.permissions.savePermissionItems([HomePermissionItem(id: "training", name: "培训", uri: "/training")])
let model = HomeViewModel(appStore: appStore, commonMenuStore: HomeCommonMenuStore(defaults: defaults))
model.rebuildCommonMenus()
#expect(model.commonMenus.filter { $0.uri == "/training" }.count == (accountType == .storeUser ? 1 : 0))
}
}
#expect(HomeMenuCatalog.item(for: "/training")?.title == "培训中心")
}
@@ -0,0 +1,604 @@
import Foundation
import Testing
import UIKit
@testable import suixinkan
/// 注入一次失败,验证重试仍保持同一请求内容。
private actor TrainingExamFailureCounter {
private var value = 0
/// 返回本次调用序号。
func next() -> Int { value += 1; return value }
}
/// 为当前页失败和恢复测试建立稀疏草稿响应。
private enum TrainingExamDraftFixtures {
/// 仅返回请求题位范围内的答案,元信息仍覆盖完整试卷。
static func page(total: Int, revision: Int, answers: [Int: [String]], offset: Int, limit: Int) -> TrainingDraftPage {
let orders = answers.filter { !$0.value.isEmpty }.keys.sorted()
let end = min(total, offset + limit)
let items = limit > 0 ? orders.filter { $0 > offset && $0 <= end }.map {
TrainingDraftAnswerItem(questionID: "q\($0)", order: $0, selectedOptionIDs: answers[$0] ?? [])
} : []
return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: revision,
savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: orders.count,
answeredQuestionOrders: orders, total: total, offset: offset,
nextOffset: limit > 0 && end < total ? end : nil, hasMore: limit > 0 && end < total, items: items)
}
}
/// 可在请求之间切换的业务身份,不依赖 AppStore 单例。
@MainActor
private final class TrainingExamTestIdentity {
var context: TrainingContext?
/// 固定测试开始时的账号范围。
init(_ context: TrainingContext) { self.context = context }
}
/// 正式分页答题、版本保存及未知交卷恢复测试;全部使用内存网络替身。
@Suite("培训中心正式答题与交卷恢复")
@MainActor
struct TrainingRemoteExamTests {
private let context = TrainingContext(accountScope: "exam_user", scenicID: 10, storeID: 3)
private func makeDefaults() throws -> (name: String, defaults: UserDefaults) {
let name = "TrainingRemoteExamTests-\(UUID().uuidString)"
return (name, try #require(UserDefaults(suiteName: name)))
}
private func makeModel(defaults: UserDefaults, identity: TrainingExamTestIdentity? = nil) -> TrainingRemoteExamViewModel {
let scope = identity?.context ?? context
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { if let identity { return identity.context }; return scope })
}
@Test("500题恢复和随机跳题只下载所在页,已答状态来自全局题号")
func lazyPagesAndGlobalAnswers() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 500
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 6, answers: ["q401": ["A"], "q500": ["B"]], lastOrder: 401)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
#expect(model.currentIndex == 400)
#expect(model.currentQuestion?.id == "q401")
#expect(model.currentSelectedIDs == ["A"])
#expect(model.answeredCount == 2)
#expect(model.firstUnansweredIndex == 0)
await model.goToQuestion(499, service: source)
#expect(model.currentSelectedIDs == ["B"])
await model.goToQuestion(400, service: source)
await model.goToQuestion(500, service: source)
#expect(model.currentIndex == 400)
let calls = await source.calls
#expect(calls.filter { $0.name == "questions" }.map(\.offset) == [400, 490])
#expect(calls.filter { $0.name == "questions" }.allSatisfy { $0.limit == 10 })
#expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 10])
#expect(model.answeredQuestionOrders == [401, 500])
}
@Test("响应按字节预算缩页时,随机目标直接补取而不扫描全卷")
func shortPageRandomAccess() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionsHandler = { offset, _ in
let end = min(30, offset + 3)
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
nextOffset: end < 30 ? end : nil, hasMore: end < 30,
items: ((offset + 1)...end).map(TrainingRemoteFixtures.question))
}
configuration.draftHandler = { offset, limit in
let end = limit == 0 ? offset : min(30, offset + 3)
let items: [TrainingDraftAnswerItem] = limit > 0 && offset < 19 && end >= 19
? [TrainingDraftAnswerItem(questionID: "q19", order: 19, selectedOptionIDs: ["B"])] : []
return TrainingDraftPage(taskID: "task_1", paperSnapshotID: "paper_1", draftRevision: 1,
savedAt: TrainingRemoteFixtures.now, lastQuestionOrder: 1, answeredCount: 1,
answeredQuestionOrders: [19], total: 30, offset: offset,
nextOffset: limit > 0 && end < 30 ? end : nil, hasMore: limit > 0 && end < 30, items: items)
}
configuration.saveHandler = { request in
TrainingDraftConfirmation(draftRevision: request.baseRevision, savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
}
let source = TrainingDataStub(configuration: configuration)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await model.goToQuestion(18, service: source)
#expect(model.currentQuestion?.id == "q19")
#expect(model.currentSelectedIDs == ["B"])
#expect(model.firstUnansweredIndex == 0)
let calls = await source.calls
#expect(calls.filter { $0.name == "questions" }.map(\.offset) == [0, 10, 18])
#expect(calls.filter { $0.name == "draft" && $0.limit != 0 }.map(\.offset) == [0, 10, 18])
}
@Test("全部已答即使只缓存一页也可交卷,不全量读取或回传草稿")
func submitSavedRevisionWithoutReadingWholeDraft() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 500
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 15, answers: Dictionary(uniqueKeysWithValues: (1...500).map { ("q\($0)", ["A"]) }))
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
#expect(model.answeredCount == 500)
#expect(model.firstUnansweredIndex == nil)
#expect(await model.submit(service: source)?.id == "attempt_1")
let requests = await source.submissionRequests
#expect(requests.count == 1)
#expect(requests.first?.draftRevision == 15)
#expect(requests.first?.paperSnapshotID == "paper_1")
let calls = await source.calls
#expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10])
#expect(calls.filter { $0.name == "questions" }.count == 1)
#expect(!model.hasPendingSubmission)
#expect(model.submittedResult?.attempt.id == "attempt_1")
}
@Test("选择仅保存一题变化且使用最新确认版本")
func incrementalSaveAndRevision() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let source = TrainingDataStub()
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await model.select(optionID: "A", service: source)
#expect(model.draftRevision == 2)
#expect(model.answeredQuestionOrders == [1])
await model.select(optionID: "B", service: source)
let requests = await source.savedRequests
#expect(requests.map(\.baseRevision) == [1, 2])
#expect(requests.allSatisfy { $0.changes.count == 1 && $0.changes.first?.questionID == "q1" })
#expect(requests.last?.changes.first?.selectedOptionIDs == ["B"])
#expect(requests[0].requestID != requests[1].requestID)
#expect(model.currentSelectedIDs == ["B"])
#expect(model.answeredCount == 1)
}
@Test("多选切换提交规范化集合,取消一项不丢失其它选择")
func multipleChoiceIncrementalToggle() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionsHandler = { offset, limit in
let end = min(30, offset + limit)
let questions = ((offset + 1)...end).map { order -> TrainingQuestionItem in
let original = TrainingRemoteFixtures.question(order)
return TrainingQuestionItem(id: original.id, order: order, type: order == 1 ? .multiple : .single,
stem: original.stem, options: original.options)
}
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: questions)
}
let source = TrainingDataStub(configuration: configuration)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await model.select(optionID: "A", service: source)
await model.select(optionID: "B", service: source)
await model.select(optionID: "A", service: source)
#expect(model.currentSelectedIDs == ["B"])
#expect((await source.savedRequests).map { $0.changes.first?.selectedOptionIDs } == [["A"], ["A", "B"], ["B"]])
#expect(model.answeredCount == 1)
}
@Test("保存超时暂停编辑,重试同ID同版本同内容")
func saveFailureRetainsOriginalRequest() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let counter = TrainingExamFailureCounter()
var configuration = TrainingDataStub.Configuration()
configuration.saveHandler = { request in
if await counter.next() == 1 { throw URLError(.timedOut) }
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1, savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
}
let source = TrainingDataStub(configuration: configuration)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await model.select(optionID: "A", service: source)
#expect(model.hasPendingMutation)
#expect(!model.canEdit)
#expect(model.currentSelectedIDs.isEmpty)
await model.select(optionID: "B", service: source)
#expect(await source.savedRequests.count == 1)
await model.retryMutation(service: source)
let requests = await source.savedRequests
#expect(requests.count == 2)
#expect(requests[0] == requests[1])
#expect(model.currentSelectedIDs == ["A"])
#expect(!model.hasPendingMutation)
}
@Test("版本冲突读取最新元信息与当前页,不覆盖其它设备的新答案")
func conflictRefreshesCurrentPage() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let source = TrainingDataStub()
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await source.seedDraft(revision: 8, answers: ["q1": ["B"], "q10": ["A"]])
await model.select(optionID: "A", service: source)
#expect(model.draftRevision == 8)
#expect(model.currentSelectedIDs == ["B"])
#expect(model.answeredCount == 2)
#expect(model.errorMessage != nil)
#expect(!model.hasPendingMutation)
#expect(await source.savedRequests.count == 1)
let calls = await source.calls
#expect(calls.filter { $0.name == "draft" }.map(\.limit) == [0, 10, 0, 10])
}
@Test("重置超时沿原键恢复,成功响应含新答案时不盲清")
func resetRetryUsesCurrentDraftState() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let counter = TrainingExamFailureCounter()
var configuration = TrainingDataStub.Configuration()
configuration.resetHandler = { _ in
if await counter.next() == 1 { throw URLError(.networkConnectionLost) }
return TrainingDraftConfirmation(draftRevision: 5, savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
}
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 3, answers: ["q1": ["A"]])
let model = makeModel(defaults: domain.defaults)
await model.load(service: source, resetDraft: true)
#expect(model.hasPendingMutation)
await source.seedDraft(revision: 5, answers: ["q1": ["B"]])
await model.retryMutation(service: source)
let requests = await source.resetRequests
#expect(requests.count == 2)
#expect(requests[0] == requests[1])
#expect(model.draftRevision == 5)
#expect(model.currentSelectedIDs == ["B"])
#expect(model.answeredQuestionOrders == [1])
#expect(!model.hasPendingMutation)
}
@Test("未知交卷跨页面重建恢复;查询0条重试原请求,通过后也可找回原成绩")
func durableUnknownSubmissionRecovery() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 3
configuration.submitHandler = { _ in throw URLError(.timedOut) }
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 7, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]])
let first = makeModel(defaults: domain.defaults)
await first.load(service: source)
#expect(await first.submit(service: source) == nil)
#expect(first.hasPendingSubmission)
#expect(!first.canEdit)
let stored = try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context)
let saved = try #require(stored)
let second = makeModel(defaults: domain.defaults)
await second.load(service: source)
#expect(second.hasPendingSubmission)
let requests = await source.submissionRequests
#expect(requests.count == 2)
#expect(requests[0] == requests[1])
#expect(requests[1] == saved.request)
await source.configure {
$0.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) }
$0.attemptsHandler = { _, _, _ in
TrainingCursorPage(items: [TrainingRemoteFixtures.attempt()], nextCursor: nil, hasMore: false, serverTime: nil)
}
}
let restored = makeModel(defaults: domain.defaults)
await restored.load(service: source)
#expect(restored.submittedAttempt?.id == "attempt_1")
#expect(restored.submittedResult?.taskState.canRetry == false)
#expect(!restored.hasPendingSubmission)
#expect(await source.submissionRequests.count == 2)
#expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil)
}
@Test("账号景区店铺隔离待确认请求,身份切换不消费旧账号记录")
func pendingScopeAndIdentityIsolation() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let store = TrainingPendingSubmissionStore(defaults: domain.defaults)
let pending = TrainingPendingSubmission(taskID: "task_1", request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 4), context: context)
try store.save(pending)
for different in [TrainingContext(accountScope: "other", scenicID: 10, storeID: 3),
TrainingContext(accountScope: context.accountScope, scenicID: 11, storeID: 3),
TrainingContext(accountScope: context.accountScope, scenicID: 10, storeID: 4)] {
#expect(try store.load(taskID: "task_1", context: different) == nil)
}
let identity = TrainingExamTestIdentity(TrainingContext(accountScope: "other", scenicID: 10, storeID: 3))
let source = TrainingDataStub()
await source.seedDraft(revision: 2, answers: ["q1": ["B"]])
let model = makeModel(defaults: domain.defaults, identity: identity)
await model.load(service: source)
#expect(model.currentQuestion?.id == "q1")
#expect(model.currentSelectedIDs == ["B"])
#expect(!model.hasPendingSubmission)
#expect(!(await source.calls).contains { $0.name == "attempts" || $0.name == "submit" })
#expect(try store.load(taskID: "task_1", context: context) == pending)
identity.context = context
await model.validateIdentity()
#expect(model.isIdentityInvalid)
#expect(model.shouldReturnToCenter)
#expect(model.currentQuestion == nil)
#expect(model.currentSelectedIDs.isEmpty)
#expect(model.task == nil && model.progress == nil && model.paper == nil)
#expect(model.answeredQuestionOrders.isEmpty)
#expect(!model.canEdit)
#expect(try store.load(taskID: "task_1", context: context) == pending)
var failedConfiguration = TrainingDataStub.Configuration()
failedConfiguration.submitHandler = { _ in throw URLError(.timedOut) }
let failed = TrainingDataStub(configuration: failedConfiguration)
identity.context = context
let original = makeModel(defaults: domain.defaults, identity: identity)
await original.load(service: failed)
#expect(original.hasPendingSubmission)
identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3)
_ = await original.submit(service: failed)
#expect(original.isIdentityInvalid)
#expect(original.shouldReturnToCenter)
#expect(original.currentQuestion == nil)
#expect(await failed.submissionRequests.count == 1)
#expect(try store.load(taskID: "task_1", context: context) == pending)
}
@Test("同任务页面不能覆盖待确认记录,交卷前优先恢复已有持久化键")
func existingPendingRequestCannotBeOverwritten() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 3
configuration.submitHandler = { _ in throw URLError(.timedOut) }
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 9, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]])
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
let store = TrainingPendingSubmissionStore(defaults: domain.defaults)
let pending = TrainingPendingSubmission(taskID: "task_1",
request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 9), context: context)
try store.save(pending)
let replacement = TrainingPendingSubmission(taskID: "task_1",
request: TrainingSubmissionRequest(submissionID: "replacement", paperSnapshotID: "paper_1", draftRevision: 9), context: context)
#expect(throws: TrainingPendingSubmissionError.alreadyPending) { try store.save(replacement) }
#expect(await model.submit(service: source) == nil)
#expect(await source.submissionRequests == [pending.request])
#expect(try store.load(taskID: "task_1", context: context) == pending)
}
@Test("服务端已完成资格阻止读取试卷和新的交卷")
func completedGatePreventsNewSubmission() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.progressHandler = { _ in TrainingRemoteFixtures.progress(completed: true) }
let source = TrainingDataStub(configuration: configuration)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
#expect(!model.canEdit)
#expect(await model.submit(service: source) == nil)
#expect(!(await source.calls).contains { $0.name == "paper" || $0.name == "questions" || $0.name == "submit" })
}
@Test("明确漏答业务拒绝释放待确认请求,并恢复最新漏答题号")
func definiteRejectionReleasesPendingSubmission() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 3
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 4, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]])
await source.configure {
$0.submitHandler = { request in
await source.seedDraft(revision: request.draftRevision, answers: ["q1": ["A"], "q2": ["A"]])
throw TrainingRemoteError.answerIncomplete("第3题尚未作答")
}
}
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
#expect(await model.submit(service: source) == nil)
#expect(!model.hasPendingSubmission)
#expect(model.answeredCount == 2)
#expect(model.firstUnansweredIndex == 2)
#expect(try TrainingPendingSubmissionStore(defaults: domain.defaults).load(taskID: "task_1", context: context) == nil)
}
@Test("题目成功而草稿页失败时禁止编辑,多选恢复后保留原B再加入A")
func failedDraftPageCannotOverwriteUnloadedAnswers() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let counter = TrainingExamFailureCounter()
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 20
configuration.questionsHandler = { offset, limit in
let end = min(20, offset + limit)
let items = ((offset + 1)...end).map { order -> TrainingQuestionItem in
let original = TrainingRemoteFixtures.question(order)
return TrainingQuestionItem(id: original.id, order: order, type: order == 11 ? .multiple : .single,
stem: original.stem, options: original.options)
}
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 20, offset: offset,
nextOffset: end < 20 ? end : nil, hasMore: end < 20, items: items)
}
configuration.draftHandler = { offset, limit in
if offset == 10, limit > 0, await counter.next() == 1 { throw URLError(.timedOut) }
return TrainingExamDraftFixtures.page(total: 20, revision: 3, answers: [1: ["A"], 11: ["B"]], offset: offset, limit: limit)
}
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 3, answers: ["q1": ["A"], "q11": ["B"]])
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await model.goToQuestion(10, service: source)
#expect(model.currentQuestion?.id == "q11")
#expect(!model.isCurrentPageReady)
#expect(!model.canEdit)
#expect(model.canRetryCurrentPage)
await model.select(optionID: "A", service: source)
#expect(await source.savedRequests.isEmpty)
await model.retryCurrentPage(service: source)
#expect(model.currentSelectedIDs == ["B"])
#expect(model.canEdit)
await model.select(optionID: "A", service: source)
#expect((await source.savedRequests).last?.changes.first?.selectedOptionIDs == ["A", "B"])
await model.goToQuestion(0, service: source)
#expect(model.currentSelectedIDs == ["A"])
#expect((await source.calls).filter { $0.name == "draft" && $0.offset == 0 }.count == 2)
}
@Test("冲突后元信息刷新断网仍有当前页重试入口,不会永久锁页")
func conflictRefreshFailureCanRetryCurrentPage() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let source = TrainingDataStub()
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
await source.seedDraft(revision: 8, answers: ["q1": ["B"]])
let counter = TrainingExamFailureCounter()
await source.configure {
$0.draftHandler = { offset, limit in
if await counter.next() == 1 { throw URLError(.networkConnectionLost) }
return TrainingExamDraftFixtures.page(total: 30, revision: 8, answers: [1: ["B"]], offset: offset, limit: limit)
}
}
await model.select(optionID: "A", service: source)
#expect(!model.canEdit)
#expect(model.canRetryCurrentPage)
#expect(!model.hasPendingMutation)
await model.retryCurrentPage(service: source)
#expect(model.currentSelectedIDs == ["B"])
#expect(model.draftRevision == 8)
#expect(model.canEdit)
#expect(await source.savedRequests.count == 1)
}
@Test("交卷成功时考试页被覆盖,返回后仍直接进入已有成绩")
func coveredExamPresentsCompletedResultWhenVisibleAgain() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 3
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]])
let model = makeModel(defaults: domain.defaults)
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
let navigation = UINavigationController(rootViewController: controller)
let window = try makeWindow(navigation)
defer { window.isHidden = true }
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
#expect(model.canEdit)
try await settleTransitions(in: navigation)
let covering = UIViewController()
navigation.pushViewController(covering, animated: false)
try await settleTransitions(in: navigation)
#expect(await model.submit(service: source)?.id == "attempt_1")
#expect(navigation.topViewController === covering)
navigation.popViewController(animated: true)
let resultDeadline = ContinuousClock.now.advanced(by: .seconds(3))
while !(navigation.topViewController is TrainingResultViewController), ContinuousClock.now < resultDeadline {
try await Task.sleep(for: .milliseconds(10))
}
try await settleTransitions(in: navigation)
#expect(navigation.topViewController is TrainingResultViewController)
#expect(!(await source.calls).contains { $0.name == "attempt" })
}
@Test("身份切换后返回考试页清理旧数据并退出根页面,保留未知交卷键")
func changedIdentityReturnsToRootWithoutConsumingSubmission() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.questionCount = 3
configuration.submitHandler = { _ in throw URLError(.timedOut) }
let source = TrainingDataStub(configuration: configuration)
await source.seedDraft(revision: 2, answers: ["q1": ["A"], "q2": ["A"], "q3": ["A"]])
let identity = TrainingExamTestIdentity(context)
let model = makeModel(defaults: domain.defaults, identity: identity)
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
let root = UIViewController()
let center = TrainingCenterViewController(service: source)
let navigation = UINavigationController()
navigation.setViewControllers([root, center, controller], animated: false)
let window = try makeWindow(navigation)
defer { window.isHidden = true }
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while !model.canEdit, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
#expect(model.canEdit)
try await settleTransitions(in: navigation)
let covering = UIViewController()
navigation.pushViewController(covering, animated: false)
try await settleTransitions(in: navigation)
#expect(await model.submit(service: source) == nil)
let store = TrainingPendingSubmissionStore(defaults: domain.defaults)
let stored = try store.load(taskID: "task_1", context: context)
let pending = try #require(stored)
identity.context = TrainingContext(accountScope: "other", scenicID: 10, storeID: 3)
navigation.popViewController(animated: true)
let exitDeadline = ContinuousClock.now.advanced(by: .seconds(3))
while navigation.topViewController !== root, ContinuousClock.now < exitDeadline {
try await Task.sleep(for: .milliseconds(10))
}
try await settleTransitions(in: navigation)
#expect(navigation.topViewController === root)
#expect(model.isIdentityInvalid && model.shouldReturnToCenter)
#expect(model.currentQuestion == nil && model.submittedAttempt == nil)
#expect(try store.load(taskID: "task_1", context: context) == pending)
#expect(await source.submissionRequests.count == 1)
}
private func makeWindow(_ navigation: UINavigationController) throws -> UIWindow {
let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
window.rootViewController = navigation
navigation.beginAppearanceTransition(true, animated: false)
window.isHidden = false
navigation.endAppearanceTransition()
navigation.view.layoutIfNeeded()
return window
}
private func settleTransitions(in navigation: UINavigationController) async throws {
// 非动画栈替换也可能在当前 main loop 中尚未结束。
try await Task.sleep(for: .milliseconds(20))
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while navigation.transitionCoordinator != nil, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
#expect(navigation.transitionCoordinator == nil)
}
@Test("再次加载重考页刷新资格但不重复清稿")
func returningExamDoesNotRepeatInitialReset() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
let source = TrainingDataStub()
await source.seedDraft(revision: 3, answers: ["q1": ["A"]])
let model = makeModel(defaults: domain.defaults)
await model.load(service: source, resetDraft: true)
await model.select(optionID: "B", service: source)
await model.load(service: source, resetDraft: true)
#expect(await source.resetRequests.count == 1)
#expect(model.currentSelectedIDs == ["B"])
}
@Test("未知交卷恢复遇权限拒绝请求退出考试,但保留原持久化提交键")
func forbiddenRecoveryRetainsOriginalSubmission() async throws {
let domain = try makeDefaults()
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
var configuration = TrainingDataStub.Configuration()
configuration.submitHandler = { _ in throw TrainingRemoteError.forbidden("任务暂不可访问") }
let source = TrainingDataStub(configuration: configuration)
let store = TrainingPendingSubmissionStore(defaults: domain.defaults)
let pending = TrainingPendingSubmission(taskID: "task_1",
request: TrainingSubmissionRequest(submissionID: "original", paperSnapshotID: "paper_1", draftRevision: 3), context: context)
try store.save(pending)
let model = makeModel(defaults: domain.defaults)
await model.load(service: source)
#expect(model.shouldReturnToCenter)
#expect(model.hasPendingSubmission)
#expect(try store.load(taskID: "task_1", context: context) == pending)
#expect(await source.submissionRequests == [pending.request])
}
}
@@ -0,0 +1,112 @@
import Foundation
import Testing
@testable import suixinkan
/// 任务和成绩的分页、请求边界与缓存复用回归。
@Suite("正式培训摘要与解析")
struct TrainingRemoteListTests {
@Test("首页只请求概览与三条任务摘要")
func homeUsesSmallResources() async {
let source = TrainingDataStub()
let model = TrainingRemoteCenterViewModel()
await model.load(service: source)
let calls = await source.calls
#expect(Set(calls.map(\.name)) == Set(["summary", "tasks"]))
#expect(calls.first { $0.name == "tasks" }?.limit == 3)
#expect(model.tasks.count == 1)
#expect(model.latestScore == "—")
}
@Test("任务筛选传给服务端,用户翻页才消费游标")
func serverFilteringAndPagination() async {
let source = TrainingDataStub()
await source.configure {
$0.tasksHandler = { status, keyword, cursor, _ in
#expect(status == .completed)
#expect(keyword == "服务")
return TrainingCursorPage(items: [TrainingRemoteFixtures.task(id: cursor == nil ? "first" : "second")], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
}
}
let model = TrainingRemoteCenterViewModel()
model.selectTab(.tasks)
model.filter = .completed
model.keyword = " 服务 "
await model.load(service: source)
#expect(model.tasks.map(\.id) == ["first"])
#expect(model.hasMore)
await model.loadMore(service: source)
#expect(model.tasks.map(\.id) == ["first", "second"])
#expect(!model.hasMore)
#expect(await source.calls.count == 3)
}
@Test("记录页不读取任务、试卷或课程")
func recordsAreIndependent() async {
let source = TrainingDataStub()
let model = TrainingRemoteCenterViewModel()
model.selectTab(.records)
await model.load(service: source)
#expect(Set(await source.calls.map(\.name)) == Set(["summary", "attempts"]))
}
@Test("成绩首屏不预取解析,展开后只取一页并复用")
func reviewsAreLazyAndCached() async {
let source = TrainingDataStub()
let model = TrainingRemoteResultViewModel(attemptID: "attempt_1")
await model.load(service: source)
#expect(await source.calls.map(\.name) == ["attempt"])
#expect(model.reviews.isEmpty)
await model.loadReviews(service: source)
await model.loadReviews(service: source)
#expect(model.reviews.count == 1)
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
}
@Test("解析失败保留成绩并能重试")
func reviewsFailureDoesNotHideScore() async {
let source = TrainingDataStub()
await source.configure { $0.reviewsHandler = { _ in throw APIError.networkFailed("离线") } }
let model = TrainingRemoteResultViewModel(attemptID: "attempt_1")
await model.load(service: source)
await model.loadReviews(service: source)
#expect(model.detail != nil)
#expect(model.reviewErrorMessage != nil)
await source.configure { $0.reviewsHandler = nil }
await model.loadReviews(service: source)
#expect(model.hasLoadedReviews)
}
@Test("刷新成绩后解析不可用时移除此前缓存")
func reviewAvailabilityClearsCachedPages() async {
let source = TrainingDataStub()
let model = TrainingRemoteResultViewModel(attemptID: "attempt_1")
await model.load(service: source)
await model.loadReviews(service: source)
#expect(!model.reviews.isEmpty)
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(reviewAvailable: false) } }
await model.load(service: source)
#expect(model.detail != nil)
#expect(model.reviews.isEmpty)
#expect(!model.hasLoadedReviews)
await model.loadReviews(service: source)
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
}
@Test("身份变化或权限撤回后清空已缓存成绩与解析", arguments: [TrainingRemoteError.identityChanged, .forbidden("任务权限已撤回")])
func identityChangeClearsCachedResult(error: TrainingRemoteError) async {
let source = TrainingDataStub()
await source.configure { $0.reviewsHandler = { _ in
TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: "next", hasMore: true)
} }
let model = TrainingRemoteResultViewModel(attemptID: "attempt_1")
await model.load(service: source)
await model.loadReviews(service: source)
#expect(!model.reviews.isEmpty)
await source.configure { $0.reviewsHandler = { _ in throw error } }
await model.loadReviews(service: source, nextPage: true)
#expect(model.isIdentityInvalid == (error == .identityChanged))
#expect(model.isAccessRevoked == (error.code == 150101))
#expect(model.detail == nil)
#expect(model.reviews.isEmpty)
}
}
@@ -0,0 +1,491 @@
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("已读完的只读课程不新建学习会话")
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<TrainingSectionContent, Never>?
private var waiters: [CheckedContinuation<Void, Never>] = []
/// 等待测试明确释放正文,通知等待请求已发出的测试代码。
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: "<p>旧账号课程</p>"))
response = nil
}
}
/// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。
private actor TrainingReadingHeartbeatGate {
private var response: CheckedContinuation<Void, Never>?
private var waiters: [CheckedContinuation<Void, Never>] = []
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
}
+38 -16
View File
@@ -14,7 +14,7 @@ struct TrainingUIRenderingTests {
defer { try? FileManager.default.removeItem(at: directory) }
let source = TrainingDemoService(context: TrainingContext(accountScope: "render", scenicID: 1, storeID: 1),
storage: TrainingDemoFileStorage(directory: directory))
let controller = TrainingCenterViewController(service: source)
let controller = TrainingCenterViewController(service: TrainingDataStub())
controller.loadViewIfNeeded()
await controller.reload()
let navigation = UINavigationController(rootViewController: controller)
@@ -23,8 +23,8 @@ struct TrainingUIRenderingTests {
navigation.view.layoutIfNeeded()
Attachment.record(render(navigation.view), named: "培训首页", as: .png)
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
#expect(labels.contains { $0.text == "一线服务规范学习(演示)" })
#expect(labels.contains { $0.text?.contains("未同步景区后台") == true })
#expect(labels.contains { $0.text == "一线服务规范学习" })
#expect(!labels.contains { $0.text?.contains("未同步景区后台") == true })
let original = try await source.task(id: "demo-service")
let longTask = TrainingTask(id: original.id, title: String(repeating: "游客沟通与接待服务规范培训", count: 3),
@@ -58,50 +58,62 @@ struct TrainingUIRenderingTests {
@Test("未通过成绩可展开解析并返回已有课程,旧失败成绩在通过后不可重考")
func resultLearningAndReviewNavigation() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let source = TrainingDemoService(context: TrainingContext(accountScope: "result-render", scenicID: 1, storeID: 1), storage: TrainingDemoFileStorage(directory: directory))
for _ in 0..<20 { _ = try await source.recordReadingSecond(taskID: "demo-service") }
let wrong: TrainingAnswers = ["q1": ["B"], "q2": ["C"], "q3": ["A"], "q4": ["D"]]
let attempt = try await source.submit(taskID: "demo-service", answers: wrong, submissionID: "failed")
let source = TrainingDataStub()
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } }
let attempt = TrainingRemoteFixtures.attempt(passed: false)
let center = TrainingCenterViewController(service: source)
let course = TrainingCourseViewController(taskID: "demo-service", service: source)
let result = TrainingResultViewController(taskID: "demo-service", attemptID: attempt.id, service: source)
let course = TrainingCourseViewController(taskID: "task_1", service: source)
let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source)
let navigation = UINavigationController()
navigation.setViewControllers([center, course, result], animated: false)
let window = try makeWindow(navigation)
defer { window.isHidden = true }
result.loadViewIfNeeded()
await result.reload()
try await settleTransitions(in: navigation)
navigation.view.layoutIfNeeded()
let learning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
let details = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.details" })
let action = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" })
#expect(action.configuration?.title == "再考一次")
#expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem })
#expect(!allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem })
Attachment.record(render(navigation.view), named: "未通过成绩默认收起解析", as: .png)
details.sendActions(for: .touchUpInside)
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while !allViews(result.view).compactMap({ $0 as? UILabel }).contains(where: { $0.text == TrainingRemoteFixtures.review().stem }), ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
navigation.view.layoutIfNeeded()
#expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == attempt.reviews.first?.question.stem })
#expect(allViews(result.view).compactMap { $0 as? UILabel }.contains { $0.text == TrainingRemoteFixtures.review().stem })
Attachment.record(render(navigation.view), named: "成绩答案解析展开", as: .png)
learning.sendActions(for: .touchUpInside)
try await settleTransitions(in: navigation)
#expect(navigation.topViewController === course)
navigation.setViewControllers([center, result], animated: false)
try await settleTransitions(in: navigation)
await result.reload()
let newLearning = try #require(allViews(result.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.learning" })
newLearning.sendActions(for: .touchUpInside)
#expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "demo-service")
let passed = try await source.submit(taskID: "demo-service", answers: ["q1": ["A"], "q2": ["A", "B"], "q3": ["B"], "q4": ["A", "B", "C"]], submissionID: "passed")
try await settleTransitions(in: navigation)
#expect((navigation.topViewController as? TrainingCourseViewController)?.taskID == "task_1")
await source.configure { $0.attemptHandler = { _ in
TrainingAttemptDetail(attempt: TrainingRemoteFixtures.attempt(passed: false), taskState: TrainingRemoteFixtures.result(passed: true).taskState, serverTime: TrainingRemoteFixtures.now)
} }
let passed = TrainingRemoteFixtures.attempt(passed: true)
navigation.setViewControllers([center, result], animated: false)
try await settleTransitions(in: navigation)
await result.reload()
#expect(action.configuration?.title == "完成,返回培训中心")
let passedResult = TrainingResultViewController(taskID: "demo-service", attemptID: passed.id, service: source)
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } }
let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source)
navigation.setViewControllers([center, passedResult], animated: false)
try await settleTransitions(in: navigation)
await passedResult.reload()
navigation.view.layoutIfNeeded()
Attachment.record(render(navigation.view), named: "通过成绩仍可返回学习", as: .png)
let completion = try #require(allViews(passedResult.view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "training.result.action" })
completion.sendActions(for: .touchUpInside)
try await settleTransitions(in: navigation)
#expect(navigation.topViewController === center)
}
@@ -146,6 +158,16 @@ struct TrainingUIRenderingTests {
Attachment.record(image, named: "100题答题卡", as: .png)
}
/// 前一导航动画结束后再执行后续操作,避免测试同时驱动互相冲突的转场。
private func settleTransitions(in navigation: UINavigationController) async throws {
await Task.yield()
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while navigation.transitionCoordinator != nil, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
#expect(navigation.transitionCoordinator == nil)
}
/// 按实际可见状态等待差异化列表动画,超时后让测试明确失败。
private func waitForVisibleCell(at indexPath: IndexPath, in collection: UICollectionView) async throws -> UICollectionViewCell {
let deadline = ContinuousClock.now.advanced(by: .seconds(3))