import Foundation import XCTest @testable import suixinkan /// 验证准备页只读取购买配置、选择约束及异步身份隔离。 @MainActor final class DroneDockPreparationViewModelTests: XCTestCase { /// 次数和配置来自购买快照,首页旧额度不会覆盖五次套餐。 func testPurchasedSnapshotOwnsCountsPointsAndRoutes() async throws { let service = try ImmediatePreparationService() let model = try makeModel(service: service) await model.refresh() XCTAssertEqual(model.projectInfo?.order.shotTotal, 5) XCTAssertEqual(model.projectInfo?.order.shotUsed, 0) XCTAssertEqual(model.projectInfo?.order.shotRemain, 5) XCTAssertEqual(model.spots.map(\.id), [201, 202]) XCTAssertEqual(model.selectedSpotID, 201) XCTAssertEqual(model.selectedRouteID, 301) XCTAssertEqual(model.selectedSpot?.name, "已购点位 201") XCTAssertEqual(model.routes.map(\.id), [301, 302]) XCTAssertNil(model.errorMessage) XCTAssertEqual(service.projectRequests.first?.projectID, 101) XCTAssertEqual(service.projectRequests.first?.orderNumber, "TEST-PREPARATION-001") XCTAssertEqual(service.projectRequests.count, 1) } /// 页面刷新只发 project-info GET,不触发定位、旧设备入口或任务写入。 func testRefreshOnlyRequestsProjectInfo() async throws { let payload = Data(#"{"code":100000,"msg":"success","data":{"order_number":"TEST-PREPARATION-001","project_id":101,"project_name":"已购五次套餐","shoot_count":5,"shot_count":0,"remaining_count":5,"can_create_task":true,"spot":[]}}"#.utf8) let session = MockURLSession(responses: [payload]) let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session)) let model = try makeModel(service: api) await model.refresh() XCTAssertEqual(session.requests.count, 1) let request = try XCTUnwrap(session.requests.first) XCTAssertEqual(request.httpMethod, "GET") XCTAssertEqual(request.url?.path, "/api/yf-handset-app/photog/multi-plane/project-info") let items = try XCTUnwrap(URLComponents(url: XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems) XCTAssertEqual(Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") }), ["scenic_id": "128", "project_id": "101", "order_number": "TEST-PREPARATION-001"]) XCTAssertNotNil(model.projectInfo) XCTAssertNil(model.errorMessage) } /// 已购配置不包含实时设备与定位数据,展示保持未知且不开放召唤。 func testValidPurchaseKeepsDeviceAndLocationUnknown() async throws { let model = try makeModel(service: ImmediatePreparationService()) await model.refresh() XCTAssertEqual(model.connectionTitle, "机巢连接待确认") XCTAssertEqual(model.connectionTone, .gray) XCTAssertEqual(model.deviceStatusText, "状态待确认") XCTAssertEqual(model.deviceTone, .gray) XCTAssertEqual(model.primaryButtonTitle, "确认并召唤") XCTAssertEqual(model.admissionMessage, "召唤功能暂未开放") } /// 点位切换重选所属航线,未知及不可用航线不能成为当前选择。 func testChangingSpotRejectsUnavailableAndForeignRoutes() async throws { let service = try ImmediatePreparationService() var second = PreparationFixture.point(202, routes: [401, 402, 403]) var routes = try XCTUnwrap(second["air_lines"] as? [[String: Any]]) routes[0]["available"] = false routes[2]["available"] = NSNull() second["air_lines"] = routes service.projectResult = .success(try PreparationFixture.project(spots: [PreparationFixture.point(201), second])) let model = try makeModel(service: service) await model.refresh() model.selectRoute(id: 302) XCTAssertEqual(model.selectedRouteID, 302) model.selectSpot(id: 202) XCTAssertEqual(model.selectedRouteID, 402) for id in [301, 401, 403, 999] { model.selectRoute(id: id) } XCTAssertEqual(model.selectedRouteID, 402) XCTAssertEqual(service.projectRequests.count, 1) } /// 刷新保留仍可用选择,已停用点位或航线回落到首个明确可用项。 func testRefreshRevalidatesAvailabilityAndSelection() async throws { let service = try ImmediatePreparationService() let model = try makeModel(service: service) await model.refresh() model.selectSpot(id: 202) model.selectRoute(id: 402) await model.refresh() XCTAssertEqual(model.selectedRouteID, 402) service.projectResult = .success(try PreparationFixture.project(spots: [PreparationFixture.point(202, routes: [401])])) await model.refresh() XCTAssertEqual(model.selectedSpotID, 202) XCTAssertEqual(model.selectedRouteID, 401) service.projectResult = .success(try PreparationFixture.project(spots: [PreparationFixture.point(201, routes: [301, 401])])) await model.refresh() XCTAssertEqual(model.selectedSpotID, 201) XCTAssertEqual(model.selectedRouteID, 301, "点位被替换时不沿用旧点位的航线选择") var unavailable = PreparationFixture.point(202) unavailable["available"] = false service.projectResult = .success(try PreparationFixture.project(spots: [unavailable, PreparationFixture.point(201)])) await model.refresh() model.selectSpot(id: 202) XCTAssertEqual(model.selectedSpotID, 201) service.projectResult = .success(try PreparationFixture.project(spots: [])) await model.refresh() XCTAssertNil(model.selectedSpotID) XCTAssertNil(model.selectedRouteID) XCTAssertTrue(model.routes.isEmpty) } /// 可用性未知时不猜测可拍,仍保留已购配置供页面解释。 func testUnknownAvailabilityDoesNotSelectPoint() async throws { let service = try ImmediatePreparationService() var point = PreparationFixture.point(201) point.removeValue(forKey: "available") service.projectResult = .success(try PreparationFixture.project(spots: [point])) let model = try makeModel(service: service) await model.refresh() model.selectSpot(id: 201) XCTAssertEqual(model.spots.count, 1) XCTAssertNil(model.selectedSpotID) XCTAssertNil(model.selectedRouteID) XCTAssertEqual(model.admissionMessage, "请选择可用拍摄点") } /// 购买配置失败后清空次数与选择,不继续沿用旧快照。 func testProjectFailureClearsPurchasedDataAndRetryRestoresIt() async throws { let service = try ImmediatePreparationService() let model = try makeModel(service: service) await model.refresh() service.projectResult = .failure(APIError.networkFailed("购买配置暂不可用")) await model.refresh() XCTAssertNil(model.projectInfo) XCTAssertTrue(model.spots.isEmpty) XCTAssertNil(model.selectedSpotID) XCTAssertTrue(model.errorMessage?.contains("购买配置暂不可用") == true) service.projectResult = .success(try PreparationFixture.project()) await model.refresh() XCTAssertEqual(model.projectInfo?.order.shotRemain, 5) XCTAssertNil(model.errorMessage) } /// 刷新期间保留旧选择供展示,但不能切换尚未重新确认的配置。 func testPendingRefreshBlocksSelectionUntilPurchaseReturns() async throws { let service = SuspendedPreparationService() let firstStarted = expectation(description: "首次购买请求") let secondStarted = expectation(description: "购买刷新挂起") service.requestStarted = { if $0 == 0 { firstStarted.fulfill() } else { secondStarted.fulfill() } } defer { service.cancelAll() } let model = try makeModel(service: service) let first = Task { await model.refresh() } await fulfillment(of: [firstStarted], timeout: 2) XCTAssertEqual(model.admissionMessage, "正在获取拍摄准备信息") try service.finish(index: 0) await first.value model.selectRoute(id: 302) let second = Task { await model.refresh() } await fulfillment(of: [secondStarted], timeout: 2) model.selectSpot(id: 202) model.selectRoute(id: 301) XCTAssertEqual(model.selectedSpotID, 201) XCTAssertEqual(model.selectedRouteID, 302) try service.finish(index: 1) await second.value XCTAssertEqual(model.selectedRouteID, 302) XCTAssertFalse(model.isLoading) } /// 购买快照必须同时属于当前订单和项目。 func testMismatchedResponseIdentitiesAreRejected() async throws { let service = try ImmediatePreparationService() let model = try makeModel(service: service) service.projectResult = .success(try PreparationFixture.project(projectID: 999)) await model.refresh() XCTAssertNil(model.projectInfo) XCTAssertNotNil(model.errorMessage) service.projectResult = .success(try PreparationFixture.project(number: "OTHER-ORDER")) await model.refresh() XCTAssertNil(model.projectInfo) service.projectResult = .success(try PreparationFixture.project()) await model.refresh() XCTAssertNotNil(model.projectInfo) XCTAssertNil(model.errorMessage) } /// 购买权限与次数各自独立,未知或已耗尽不能允许新增任务。 func testAdmissionUsesPurchasedPermissionAndKnownQuota() async throws { let service = try ImmediatePreparationService() let model = try makeModel(service: service) service.projectResult = .success(try PreparationFixture.project(remaining: 0)) await model.refresh() XCTAssertEqual(model.primaryButtonTitle, "拍摄次数已用完") service.projectResult = .success(try PreparationFixture.project(remaining: nil)) await model.refresh() XCTAssertEqual(model.admissionMessage, "拍摄次数待确认,请刷新状态") service.projectResult = .success(try PreparationFixture.project(canCreate: false)) await model.refresh() XCTAssertEqual(model.admissionMessage, "当前订单暂不可新增拍摄任务,请刷新状态") } /// 账号、景区、门店、凭证变化后,旧购买响应失效。 func testIdentityChangesRejectInFlightResponse() async throws { for changed in [context(userID: "other"), context(scenicID: 129), context(storeID: 38), context(token: "other-token")] { let scope = PreparationContextBox(context()) let service = SuspendedPreparationService() let started = expectation(description: "购买请求已挂起") service.requestStarted = { _ in started.fulfill() } defer { service.cancelAll() } let model = try makeModel(service: service, scope: scope) let pending = Task { await model.refresh() } await fulfillment(of: [started], timeout: 2) scope.value = changed try service.finish(index: 0) await pending.value XCTAssertNil(model.projectInfo) XCTAssertNil(model.selectedSpotID) XCTAssertNotNil(model.errorMessage) } } /// 页面取消和主动失效后迟到的回包不能重填数据。 func testCancellationAndInvalidationRejectLateResponses() async throws { for invalidate in [false, true] { let service = SuspendedPreparationService() let started = expectation(description: "待取消请求") service.requestStarted = { _ in started.fulfill() } defer { service.cancelAll() } let model = try makeModel(service: service) let pending = Task { await model.refresh() } await fulfillment(of: [started], timeout: 2) if invalidate { model.invalidate() } else { pending.cancel() } try service.finish(index: 0) await pending.value XCTAssertNil(model.projectInfo) XCTAssertNil(model.selectedSpotID) XCTAssertFalse(model.isLoading) } } /// 新刷新先完成时,旧购买配置不能覆盖最新选择与次数。 func testOlderRefreshCannotOverwriteNewerPurchasedSnapshot() async throws { let service = SuspendedPreparationService() let firstStarted = expectation(description: "首批请求") let secondStarted = expectation(description: "第二批请求") service.requestStarted = { if $0 == 0 { firstStarted.fulfill() } else { secondStarted.fulfill() } } defer { service.cancelAll() } let model = try makeModel(service: service) let first = Task { await model.refresh() } await fulfillment(of: [firstStarted], timeout: 2) let second = Task { await model.refresh() } await fulfillment(of: [secondStarted], timeout: 2) try service.finish(index: 1, project: PreparationFixture.project(spots: [PreparationFixture.point(202, routes: [401])], remaining: 2)) await second.value try service.finish(index: 0) await first.value XCTAssertEqual(model.spots.map(\.id), [202]) XCTAssertEqual(model.selectedRouteID, 401) XCTAssertEqual(model.projectInfo?.order.shotRemain, 2) XCTAssertNil(model.errorMessage) } /// 缺少项目或会话时本地拦截,不请求当前上架项目代替购买快照。 func testMissingProjectOrSessionDoesNotCallServices() async throws { let service = try ImmediatePreparationService() let missingProject = try makeModel(service: service, projectID: nil) await missingProject.refresh() XCTAssertNotNil(missingProject.errorMessage) let missingSession = try makeModel(service: service, scope: PreparationContextBox(context(token: ""))) await missingSession.refresh() XCTAssertNotNil(missingSession.errorMessage) XCTAssertTrue(service.projectRequests.isEmpty) } /// 每例使用内存订单和会话,不接触真实账号。 private func makeModel(service: any DroneDockPreparationServing, scope: PreparationContextBox? = nil, projectID: Int? = 101) throws -> DroneDockPreparationViewModel { let scope = scope ?? PreparationContextBox(context()) var order: [String: Any] = ["order_number": "TEST-PREPARATION-001", "project_name": "旧列表套餐", "shoot_count": 9, "shot_count": 2, "remaining_count": 7] order["project_id"] = projectID let decoded = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: order)) return DroneDockPreparationViewModel(context: scope.value, order: decoded, service: service, currentContext: { scope.value }) } /// 身份参数仅在本例测试对象中变化。 private func context(userID: String = "preparation-test-user", scenicID: Int = 128, storeID: Int = 37, token: String = "preparation-test-token") -> DroneDockHomeContext { DroneDockHomeContext(userID: userID, accountType: "store_user", scenicID: scenicID, scenicName: "测试景区", storeID: storeID, photographerName: "测试人员", token: token) } } /// 购买数据使用不同于首页的名称与额度,以检测旧快照回填。 private enum PreparationFixture { /// 购买快照使用五次额度,刻意与首页旧数据不同。 static func project(spots: [[String: Any]]? = nil, projectID: Int = 101, number: String = "TEST-PREPARATION-001", remaining: Int? = 5, canCreate: Bool = true) throws -> DroneDockProjectInfoResponse { var value: [String: Any] = ["order_number": number, "project_id": projectID, "project_name": "已购五次套餐", "shoot_count": 5, "shot_count": 0, "can_create_task": canCreate, "spot": spots ?? [point(201), point(202, routes: [401, 402])]] value["remaining_count"] = remaining return try JSONDecoder().decode(DroneDockProjectInfoResponse.self, from: JSONSerialization.data(withJSONObject: value)) } /// 已购点位和航线具备明确可用性。 static func point(_ id: Int, routes: [Int] = [301, 302]) -> [String: Any] { ["scenic_spot_id": id, "scenic_spot_name": "已购点位 \(id)", "available": true, "air_lines": routes.map { id -> [String: Any] in ["air_line_id": id, "air_line_name": "已购航线 \(id)", "available": true, "samples": []] }] } } /// 主线程上的可变会话替身。 @MainActor private final class PreparationContextBox { var value: DroneDockHomeContext init(_ value: DroneDockHomeContext) { self.value = value } } /// 单一购买配置读取服务,记录当前请求身份。 @MainActor private final class ImmediatePreparationService: DroneDockPreparationServing { var projectResult: Result private(set) var projectRequests: [(scenicID: Int, projectID: Int, orderNumber: String)] = [] /// 使用匿名购买快照作为默认结果。 init() throws { projectResult = .success(try PreparationFixture.project()) } /// 记录唯一的数据读取请求,不提供设备或飞行控制入口。 func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse { projectRequests.append((scenicID, projectID, orderNumber)) return try projectResult.get() } } /// 由测试明确完成单个购买请求,精确控制乱序与取消。 @MainActor private final class SuspendedPreparationService: DroneDockPreparationServing { var requestStarted: ((Int) -> Void)? private var projects: [CheckedContinuation?] = [] /// 挂起购买读取,允许测试更改身份或发出后续刷新。 func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse { try await withCheckedThrowingContinuation { continuation in projects.append(continuation) requestStarted?(projects.count - 1) } } /// 只完成指定请求,保留其他尚未返回的请求。 func finish(index: Int, project: DroneDockProjectInfoResponse? = nil) throws { let value = try project ?? PreparationFixture.project() let continuation = projects[index] projects[index] = nil continuation?.resume(returning: value) } /// 失败退出时释放全部 continuation,避免污染其他测试。 func cancelAll() { projects.forEach { $0?.resume(throwing: CancellationError()) } projects = [] } }