feat(drone-dock): 接入已购套餐快照并固定首页无人机占位
准备页改用 project-info 购买快照,校验订单与项目身份,并按可用性选择已购点位和航线。首页在加载、空数据及失败时保留等高无人机卡片。同步相关测试与接口联调记录、响应和截图。 验证:iPhone 18 Pro 模拟器上 81 项相关测试通过。
This commit is contained in:
@@ -1,419 +1,369 @@
|
||||
import CoreLocation
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 验证真实准备页的选择、定位缺失与请求身份隔离,不访问后端或发送飞行操作。
|
||||
/// 验证准备页只读取购买配置、选择约束及异步身份隔离。
|
||||
@MainActor
|
||||
final class DroneDockPreparationViewModelTests: XCTestCase {
|
||||
/// 最新准备快照保留零次,初次按服务端顺序选取点位和航线。
|
||||
func testSuccessfulSnapshotPreservesZeroCountsAndSelectsFirstSpotAndRoute() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let location = MockLocationProvider()
|
||||
let model = try makeModel(scope: scope, service: service, location: location)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
|
||||
/// 次数和配置来自购买快照,首页旧额度不会覆盖五次套餐。
|
||||
func testPurchasedSnapshotOwnsCountsPointsAndRoutes() async throws {
|
||||
let service = try ImmediatePreparationService()
|
||||
let model = try makeModel(service: service)
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertEqual(model.response?.orderProgress?.shotUsed, 0)
|
||||
XCTAssertEqual(model.response?.orderProgress?.shotRemain, 1)
|
||||
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])
|
||||
XCTAssertTrue(model.hasLocation)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertNil(model.locationMessage)
|
||||
XCTAssertEqual(service.requests.count, 1)
|
||||
XCTAssertEqual(service.requests.first?.scenicID, 128)
|
||||
XCTAssertEqual(service.requests.first?.orderNumber, "TEST-PREPARATION-001")
|
||||
XCTAssertEqual(service.requests.first?.coordinate?.latitude, location.coordinate.latitude)
|
||||
XCTAssertEqual(service.requests.first?.coordinate?.longitude, location.coordinate.longitude)
|
||||
XCTAssertEqual(location.requestedAccuracies.count, 1)
|
||||
XCTAssertEqual(service.projectRequests.first?.projectID, 101)
|
||||
XCTAssertEqual(service.projectRequests.first?.orderNumber, "TEST-PREPARATION-001")
|
||||
XCTAssertEqual(service.projectRequests.count, 1)
|
||||
}
|
||||
|
||||
/// 点位切换重选所属航线,非法身份与其他点位的航线不会影响当前选择。
|
||||
func testChangingSpotResetsRouteAndUnknownSelectionsAreIgnored() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
/// 页面刷新只发 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.rangeTitle, "位置待确认")
|
||||
XCTAssertEqual(model.rangeTone, .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.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 401)
|
||||
XCTAssertEqual(model.routes.map(\.id), [401, 402])
|
||||
model.selectRoute(id: 402)
|
||||
model.selectSpot(id: 999)
|
||||
model.selectRoute(id: 301)
|
||||
model.selectRoute(id: 999)
|
||||
|
||||
XCTAssertEqual(model.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 402)
|
||||
XCTAssertEqual(model.selectedSpot?.id, 202)
|
||||
XCTAssertEqual(model.selectedRoute?.id, 402)
|
||||
XCTAssertEqual(service.requests.count, 1, "选择仅更新本地准备状态,不创建或召唤任务")
|
||||
for id in [301, 401, 403, 999] { model.selectRoute(id: id) }
|
||||
XCTAssertEqual(model.selectedRouteID, 402)
|
||||
XCTAssertEqual(service.projectRequests.count, 1)
|
||||
}
|
||||
|
||||
/// 刷新保留仍有效的选择,已移除的航线或点位回落到服务端首项,空列表清除选择。
|
||||
func testRefreshPreservesValidSelectionsAndReplacesRemovedSelections() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
/// 刷新保留仍可用选择,已停用点位或航线回落到首个明确可用项。
|
||||
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.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 402)
|
||||
|
||||
var changed = spots()
|
||||
changed[1]["air_lines"] = [route(id: 401)]
|
||||
service.result = .success(try response(spots: changed))
|
||||
service.projectResult = .success(try PreparationFixture.project(spots: [PreparationFixture.point(202, routes: [401])]))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 401)
|
||||
|
||||
service.result = .success(try response(spots: [spots()[0]]))
|
||||
service.projectResult = .success(try PreparationFixture.project(spots: [PreparationFixture.point(201, routes: [301, 401])]))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.selectedSpotID, 201)
|
||||
XCTAssertEqual(model.selectedRouteID, 301)
|
||||
|
||||
service.result = .success(try response(spots: []))
|
||||
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()
|
||||
XCTAssertTrue(model.spots.isEmpty)
|
||||
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)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNil(model.selectedSpot)
|
||||
XCTAssertNil(model.selectedRoute)
|
||||
}
|
||||
|
||||
/// 网络失败后旧准备数据与选项失效,重试成功才重新展示点位。
|
||||
func testRefreshFailureClearsSnapshotAndSelectionsAndCanRetry() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
/// 可用性未知时不猜测可拍,仍保留已购配置供页面解释。
|
||||
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: 202)
|
||||
service.result = .failure(APIError.networkFailed("测试准备请求超时"))
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
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)
|
||||
XCTAssertTrue(model.errorMessage?.contains("测试准备请求超时") == true)
|
||||
|
||||
service.result = .success(try response())
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertTrue(model.errorMessage?.contains("购买配置暂不可用") == true)
|
||||
service.projectResult = .success(try PreparationFixture.project())
|
||||
await model.refresh()
|
||||
XCTAssertNotNil(model.response)
|
||||
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, 301)
|
||||
XCTAssertEqual(model.selectedRouteID, 302)
|
||||
try service.finish(index: 1)
|
||||
await second.value
|
||||
XCTAssertEqual(model.selectedRouteID, 302)
|
||||
XCTAssertFalse(model.isLoading)
|
||||
}
|
||||
|
||||
/// 未定位时仍可读取点位;请求不伪造坐标,界面不信任后端缺坐标时返回的距离或范围。
|
||||
func testLocationFailureOmitsCoordinatesAndKeepsRangeUnknown() async throws {
|
||||
let location = MockLocationProvider()
|
||||
location.requestCoordinateError = LocationProviderError.permissionDenied
|
||||
let session = MockURLSession(responses: [try envelope()])
|
||||
let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
|
||||
let scope = PreparationContextBox(context())
|
||||
let model = try makeModel(scope: scope, service: api, location: location)
|
||||
|
||||
/// 购买快照必须同时属于当前订单和项目。
|
||||
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()
|
||||
|
||||
XCTAssertNotNil(model.response)
|
||||
XCTAssertFalse(model.hasLocation)
|
||||
XCTAssertNotNil(model.locationMessage)
|
||||
XCTAssertEqual(model.rangeTitle, "位置待确认")
|
||||
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)
|
||||
let request = try XCTUnwrap(session.requests.first)
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
XCTAssertEqual(request.httpMethod, "GET")
|
||||
XCTAssertEqual(request.url?.path, "/api/app/airport/workbench")
|
||||
XCTAssertNil(request.httpBody)
|
||||
let queryItems = URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
let query = Dictionary(uniqueKeysWithValues: queryItems.map { ($0.name, $0.value ?? "") })
|
||||
XCTAssertEqual(query["scenic_id"], "128")
|
||||
XCTAssertEqual(query["order_number"], "TEST-PREPARATION-001")
|
||||
XCTAssertNil(query["lat"])
|
||||
XCTAssertNil(query["lng"])
|
||||
}
|
||||
|
||||
/// 定位恢复后新请求携带新位置,原位置错误不残留在准备状态中。
|
||||
func testLocationRecoveryRefreshesCoordinateAndClearsLocationError() async throws {
|
||||
let location = MockLocationProvider()
|
||||
location.requestCoordinateError = LocationProviderError.locationFailed
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, service: service, location: location)
|
||||
/// 购买权限与次数各自独立,未知或已耗尽不能允许新增任务。
|
||||
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()
|
||||
XCTAssertFalse(model.hasLocation)
|
||||
XCTAssertNil(service.requests.first?.coordinate)
|
||||
|
||||
location.requestCoordinateError = nil
|
||||
location.coordinate = CLLocationCoordinate2D(latitude: 30.1, longitude: 120.2)
|
||||
XCTAssertEqual(model.primaryButtonTitle, "拍摄次数已用完")
|
||||
service.projectResult = .success(try PreparationFixture.project(remaining: nil))
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertTrue(model.hasLocation)
|
||||
XCTAssertNil(model.locationMessage)
|
||||
XCTAssertEqual(service.requests.last?.coordinate, DroneDockPreparationCoordinate(latitude: 30.1, longitude: 120.2))
|
||||
XCTAssertEqual(model.admissionMessage, "拍摄次数待确认,请刷新状态")
|
||||
service.projectResult = .success(try PreparationFixture.project(canCreate: false))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.admissionMessage, "当前订单暂不可新增拍摄任务,请刷新状态")
|
||||
}
|
||||
|
||||
/// 景区、顶层订单号或嵌套进度订单号不匹配时,不能展示成当前订单的准备数据。
|
||||
func testMismatchedScenicAndOrderResponsesAreRejected() async throws {
|
||||
let invalidResponses = try [
|
||||
envelope(scenicID: 999),
|
||||
envelope(orderNumber: "TEST-OTHER-ORDER"),
|
||||
envelope(progressOrderNumber: "TEST-OTHER-PROGRESS")
|
||||
]
|
||||
for payload in invalidResponses {
|
||||
let scope = PreparationContextBox(context())
|
||||
let session = MockURLSession(responses: [payload])
|
||||
let api = DroneDockPreparationAPI(client: APIClient(environment: .testing, session: session))
|
||||
let model = try makeModel(scope: scope, service: api)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号、景区、门店或凭证在等待期间变化,旧请求完成后不得展示旧订单准备数据。
|
||||
func testIdentityChangesRejectInFlightResponses() async throws {
|
||||
let changedContexts = [
|
||||
context(userID: "second-test-user"), context(scenicID: 129),
|
||||
context(storeID: 38), context(token: "second-test-token")
|
||||
]
|
||||
for (index, changedContext) in changedContexts.enumerated() {
|
||||
/// 账号、景区、门店、凭证变化后,旧购买响应失效。
|
||||
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: "准备请求已挂起 \(index)")
|
||||
let started = expectation(description: "购买请求已挂起")
|
||||
service.requestStarted = { _ in started.fulfill() }
|
||||
defer { service.cancelAll() }
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
let model = try makeModel(service: service, scope: scope)
|
||||
let pending = Task { await model.refresh() }
|
||||
await fulfillment(of: [started], timeout: 2)
|
||||
|
||||
scope.value = changedContext
|
||||
service.finish(index: 0, result: .success(try response()))
|
||||
scope.value = changed
|
||||
try service.finish(index: 0)
|
||||
await pending.value
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.projectInfo)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
/// 离页使当前请求失效,迟到的成功响应不能重新填充已清空的页面。
|
||||
func testInvalidationRejectsLateResponse() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = SuspendedPreparationService()
|
||||
let started = expectation(description: "待失效准备请求已挂起")
|
||||
service.requestStarted = { _ in started.fulfill() }
|
||||
defer { service.cancelAll() }
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
let pending = Task { await model.refresh() }
|
||||
await fulfillment(of: [started], timeout: 2)
|
||||
|
||||
model.invalidate()
|
||||
service.finish(index: 0, result: .success(try response()))
|
||||
await pending.value
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertEqual(scope.value, context(), "页面失效不得修改登录或景区选择")
|
||||
/// 页面取消和主动失效后迟到的回包不能重填数据。
|
||||
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 testOlderRefreshCannotOverwriteNewerSnapshot() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
/// 新刷新先完成时,旧购买配置不能覆盖最新选择与次数。
|
||||
func testOlderRefreshCannotOverwriteNewerPurchasedSnapshot() async throws {
|
||||
let service = SuspendedPreparationService()
|
||||
let firstStarted = expectation(description: "第一个准备请求已挂起")
|
||||
let secondStarted = expectation(description: "第二个准备请求已挂起")
|
||||
service.requestStarted = { index in
|
||||
if index == 0 { firstStarted.fulfill() }
|
||||
if index == 1 { secondStarted.fulfill() }
|
||||
}
|
||||
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(scope: scope, service: service)
|
||||
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)
|
||||
|
||||
service.finish(index: 1, result: .success(try response(spots: [spots()[1]])))
|
||||
try service.finish(index: 1, project: PreparationFixture.project(spots: [PreparationFixture.point(202, routes: [401])], remaining: 2))
|
||||
await second.value
|
||||
service.finish(index: 0, result: .success(try response()))
|
||||
try service.finish(index: 0)
|
||||
await first.value
|
||||
|
||||
XCTAssertEqual(model.spots.map(\.id), [202])
|
||||
XCTAssertEqual(model.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 401)
|
||||
XCTAssertEqual(model.projectInfo?.order.shotRemain, 2)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
}
|
||||
|
||||
/// 身份或订单编号不完整时不发出范围不明的准备请求。
|
||||
func testMissingIdentityOrOrderNumberDoesNotCallService() async throws {
|
||||
for scopeValue in [context(scenicID: 0), context(token: "")] {
|
||||
let scope = PreparationContextBox(scopeValue)
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, service: service)
|
||||
await model.refresh()
|
||||
XCTAssertTrue(service.requests.isEmpty)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
}
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
XCTAssertThrowsError(try makeModel(scope: scope, service: service, orderNumber: nil))
|
||||
XCTAssertTrue(service.requests.isEmpty)
|
||||
/// 缺少项目或会话时本地拦截,不请求当前上架项目代替购买快照。
|
||||
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(scope: PreparationContextBox, service: any DroneDockPreparationServing,
|
||||
location: MockLocationProvider = MockLocationProvider(),
|
||||
orderNumber: String? = "TEST-PREPARATION-001") throws -> DroneDockPreparationViewModel {
|
||||
var object: [String: Any] = [
|
||||
"project_id": 101, "user_phone": "130****0001", "project_name": "旧列表套餐",
|
||||
"shoot_count": 5, "shot_count": 2, "remaining_count": 3,
|
||||
"shoot_status": "processing", "order_status": 20, "can_create_task": true
|
||||
]
|
||||
object["order_number"] = orderNumber
|
||||
let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: JSONSerialization.data(withJSONObject: object))
|
||||
return DroneDockPreparationViewModel(context: scope.value, order: order, service: service,
|
||||
locationProvider: location, currentContext: { scope.value })
|
||||
/// 每例使用内存订单和会话,不接触真实账号。
|
||||
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 {
|
||||
/// 身份参数仅在本例测试对象中变化。
|
||||
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 func payload(scenicID: Int = 128, orderNumber: String = "TEST-PREPARATION-001",
|
||||
progressOrderNumber: String? = nil, spots: [[String: Any]]? = nil) -> [String: Any] {
|
||||
[
|
||||
"scenic_id": scenicID, "order_number": orderNumber,
|
||||
"order_progress": ["order_number": progressOrderNumber ?? orderNumber,
|
||||
"package_name": "测试单次套餐", "shot_total": 1, "shot_used": 0,
|
||||
"shot_remain": 1, "status_label": "待拍摄"],
|
||||
"airports": [["id": 51, "name": "测试机巢", "sn_number": "test-preparation-airport",
|
||||
"online_status": 2, "work_status": 0, "work_status_label": "离线", "metrics": []]],
|
||||
"recommend_plane": NSNull(), "spots": spots ?? self.spots(),
|
||||
"shoot_gate": ["can_shoot": false, "code": "dock_offline", "message": "机巢未连接",
|
||||
"primary_action": "blocked", "primary_action_label": "机巢未连接"],
|
||||
"tips": "测试规则提示"
|
||||
]
|
||||
}
|
||||
|
||||
/// 成功响应的内存模型供可挂起的服务替身返回。
|
||||
private func response(spots: [[String: Any]]? = nil) throws -> DroneDockPreparationResponse {
|
||||
try JSONDecoder().decode(DroneDockPreparationResponse.self,
|
||||
from: JSONSerialization.data(withJSONObject: payload(spots: spots)))
|
||||
}
|
||||
|
||||
/// 为真实 APIClient 替身构造响应包裹,验证请求及响应范围校验。
|
||||
private func envelope(scenicID: Int = 128, orderNumber: String = "TEST-PREPARATION-001",
|
||||
progressOrderNumber: String? = nil) throws -> Data {
|
||||
try JSONSerialization.data(withJSONObject: [
|
||||
"code": 100000, "msg": "success",
|
||||
"data": payload(scenicID: scenicID, orderNumber: orderNumber, progressOrderNumber: progressOrderNumber)
|
||||
])
|
||||
}
|
||||
|
||||
/// 两个匿名点位各有两条航线,便于验证跨点位选择隔离。
|
||||
private func spots() -> [[String: Any]] {
|
||||
[
|
||||
["scenic_spot_id": 201, "name": "测试点位一", "distance_label": "0 m", "distance_m": 0,
|
||||
"in_range": true, "shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [route(id: 301), route(id: 302)]],
|
||||
["scenic_spot_id": 202, "name": "测试点位二", "distance_label": "100 m", "distance_m": 100,
|
||||
"in_range": false, "shot_count": 0, "shot_status_label": "未拍摄", "air_lines": [route(id: 401), route(id: 402)]]
|
||||
]
|
||||
}
|
||||
|
||||
/// 提供真实接口字段名的匿名航线。
|
||||
private func route(id: Int) -> [String: Any] {
|
||||
["air_line_id": id, "name": "测试航线 \(id)", "estimated_fly_time": 120,
|
||||
"fly_type": 1, "line_video_duration": 15]
|
||||
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 }
|
||||
}
|
||||
|
||||
/// 准备请求参数快照,用于确认定位与订单范围不被替换。
|
||||
private struct PreparationRequestRecord {
|
||||
let scenicID: Int
|
||||
let orderNumber: String
|
||||
let coordinate: DroneDockPreparationCoordinate?
|
||||
}
|
||||
|
||||
/// 返回可替换结果的只读准备服务,不具备创建任务或控制飞行的方法。
|
||||
/// 单一购买配置读取服务,记录当前请求身份。
|
||||
@MainActor
|
||||
private final class ImmediatePreparationService: DroneDockPreparationServing {
|
||||
var result: Result<DroneDockPreparationResponse, Error>
|
||||
private(set) var requests: [PreparationRequestRecord] = []
|
||||
var projectResult: Result<DroneDockProjectInfoResponse, Error>
|
||||
private(set) var projectRequests: [(scenicID: Int, projectID: Int, orderNumber: String)] = []
|
||||
|
||||
/// 注入本例初始响应。
|
||||
init(result: Result<DroneDockPreparationResponse, Error>) { self.result = result }
|
||||
/// 使用匿名购买快照作为默认结果。
|
||||
init() throws { projectResult = .success(try PreparationFixture.project()) }
|
||||
|
||||
/// 记录读取参数并返回当前响应。
|
||||
func workbench(scenicID: Int, orderNumber: String,
|
||||
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
|
||||
requests.append(PreparationRequestRecord(scenicID: scenicID, orderNumber: orderNumber, coordinate: coordinate))
|
||||
return try result.get()
|
||||
/// 记录唯一的数据读取请求,不提供设备或飞行控制入口。
|
||||
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 continuations: [CheckedContinuation<DroneDockPreparationResponse, Error>?] = []
|
||||
private var projects: [CheckedContinuation<DroneDockProjectInfoResponse, Error>?] = []
|
||||
|
||||
/// 挂起当前请求,等待测试模拟后端回包。
|
||||
func workbench(scenicID: Int, orderNumber: String,
|
||||
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
|
||||
/// 挂起购买读取,允许测试更改身份或发出后续刷新。
|
||||
func projectInfo(scenicID: Int, projectID: Int, orderNumber: String) async throws -> DroneDockProjectInfoResponse {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
let index = continuations.count
|
||||
continuations.append(continuation)
|
||||
requestStarted?(index)
|
||||
projects.append(continuation)
|
||||
requestStarted?(projects.count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// 完成指定请求一次,防止 continuation 重复恢复。
|
||||
func finish(index: Int, result: Result<DroneDockPreparationResponse, Error>) {
|
||||
guard continuations.indices.contains(index), let continuation = continuations[index] else { return }
|
||||
continuations[index] = nil
|
||||
continuation.resume(with: result)
|
||||
/// 只完成指定请求,保留其他尚未返回的请求。
|
||||
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() {
|
||||
for index in continuations.indices { finish(index: index, result: .failure(CancellationError())) }
|
||||
projects.forEach { $0?.resume(throwing: CancellationError()) }
|
||||
projects = []
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user