feat(drone-dock): 接入真实拍摄准备页
This commit is contained in:
@@ -0,0 +1,421 @@
|
||||
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)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertEqual(model.response?.orderProgress?.shotUsed, 0)
|
||||
XCTAssertEqual(model.response?.orderProgress?.shotRemain, 1)
|
||||
XCTAssertEqual(model.spots.map(\.id), [201, 202])
|
||||
XCTAssertEqual(model.selectedSpotID, 201)
|
||||
XCTAssertEqual(model.selectedRouteID, 301)
|
||||
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)
|
||||
}
|
||||
|
||||
/// 点位切换重选所属航线,非法身份与其他点位的航线不会影响当前选择。
|
||||
func testChangingSpotResetsRouteAndUnknownSelectionsAreIgnored() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, 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, "选择仅更新本地准备状态,不创建或召唤任务")
|
||||
}
|
||||
|
||||
/// 刷新保留仍有效的选择,已移除的航线或点位回落到服务端首项,空列表清除选择。
|
||||
func testRefreshPreservesValidSelectionsAndReplacesRemovedSelections() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = ImmediatePreparationService(result: .success(try response()))
|
||||
let model = try makeModel(scope: scope, 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))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 401)
|
||||
|
||||
service.result = .success(try response(spots: [spots()[0]]))
|
||||
await model.refresh()
|
||||
XCTAssertEqual(model.selectedSpotID, 201)
|
||||
XCTAssertEqual(model.selectedRouteID, 301)
|
||||
|
||||
service.result = .success(try response(spots: []))
|
||||
await model.refresh()
|
||||
XCTAssertTrue(model.spots.isEmpty)
|
||||
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)
|
||||
await model.refresh()
|
||||
model.selectSpot(id: 202)
|
||||
service.result = .failure(APIError.networkFailed("测试准备请求超时"))
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNil(model.selectedSpotID)
|
||||
XCTAssertNil(model.selectedRouteID)
|
||||
XCTAssertTrue(model.spots.isEmpty)
|
||||
XCTAssertTrue(model.errorMessage?.contains("测试准备请求超时") == true)
|
||||
|
||||
service.result = .success(try response())
|
||||
await model.refresh()
|
||||
XCTAssertNotNil(model.response)
|
||||
XCTAssertNil(model.errorMessage)
|
||||
XCTAssertEqual(model.selectedSpotID, 201)
|
||||
XCTAssertEqual(model.selectedRouteID, 301)
|
||||
}
|
||||
|
||||
/// 未定位时仍可读取点位;请求不伪造坐标,界面不信任后端缺坐标时返回的距离或范围。
|
||||
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)
|
||||
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertNotNil(model.response)
|
||||
XCTAssertFalse(model.hasLocation)
|
||||
XCTAssertNotNil(model.locationMessage)
|
||||
XCTAssertEqual(model.rangeTitle, "位置待确认")
|
||||
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)
|
||||
await model.refresh()
|
||||
XCTAssertFalse(model.hasLocation)
|
||||
XCTAssertNil(service.requests.first?.coordinate)
|
||||
|
||||
location.requestCoordinateError = nil
|
||||
location.coordinate = CLLocationCoordinate2D(latitude: 30.1, longitude: 120.2)
|
||||
await model.refresh()
|
||||
|
||||
XCTAssertTrue(model.hasLocation)
|
||||
XCTAssertNil(model.locationMessage)
|
||||
XCTAssertEqual(service.requests.last?.coordinate, DroneDockPreparationCoordinate(latitude: 30.1, longitude: 120.2))
|
||||
}
|
||||
|
||||
/// 景区、顶层订单号或嵌套进度订单号不匹配时,不能展示成当前订单的准备数据。
|
||||
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() {
|
||||
let scope = PreparationContextBox(context())
|
||||
let service = SuspendedPreparationService()
|
||||
let started = expectation(description: "准备请求已挂起 \(index)")
|
||||
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)
|
||||
|
||||
scope.value = changedContext
|
||||
service.finish(index: 0, result: .success(try response()))
|
||||
await pending.value
|
||||
|
||||
XCTAssertNil(model.response)
|
||||
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 testOlderRefreshCannotOverwriteNewerSnapshot() async throws {
|
||||
let scope = PreparationContextBox(context())
|
||||
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() }
|
||||
}
|
||||
defer { service.cancelAll() }
|
||||
let model = try makeModel(scope: scope, 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]])))
|
||||
await second.value
|
||||
service.finish(index: 0, result: .success(try response()))
|
||||
await first.value
|
||||
|
||||
XCTAssertEqual(model.spots.map(\.id), [202])
|
||||
XCTAssertEqual(model.selectedSpotID, 202)
|
||||
XCTAssertEqual(model.selectedRouteID, 401)
|
||||
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()))
|
||||
let model = try makeModel(scope: scope, service: service, orderNumber: nil)
|
||||
await model.refresh()
|
||||
XCTAssertTrue(service.requests.isEmpty)
|
||||
XCTAssertNil(model.response)
|
||||
XCTAssertNotNil(model.errorMessage)
|
||||
}
|
||||
|
||||
/// 注入只在本例内变化的身份、网络及定位替身。
|
||||
private func makeModel(scope: PreparationContextBox, service: any DroneDockPreparationServing,
|
||||
location: MockLocationProvider = MockLocationProvider(),
|
||||
orderNumber: String? = "TEST-PREPARATION-001") throws -> DroneDockPreparationViewModel {
|
||||
var object: [String: Any] = [
|
||||
"order_id": 101, "tourist_label": "测试游客", "package_name": "旧列表套餐",
|
||||
"shot_total": 5, "shot_used": 2, "shot_remain": 3
|
||||
]
|
||||
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 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]
|
||||
}
|
||||
}
|
||||
|
||||
/// 主线程上的可变会话替身,只影响当前测试模型。
|
||||
@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] = []
|
||||
|
||||
/// 注入本例初始响应。
|
||||
init(result: Result<DroneDockPreparationResponse, Error>) { self.result = result }
|
||||
|
||||
/// 记录读取参数并返回当前响应。
|
||||
func workbench(scenicID: Int, orderNumber: String,
|
||||
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
|
||||
requests.append(PreparationRequestRecord(scenicID: scenicID, orderNumber: orderNumber, coordinate: coordinate))
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 由测试显式完成的准备请求,用于验证乱序返回与离页后的结果失效。
|
||||
@MainActor
|
||||
private final class SuspendedPreparationService: DroneDockPreparationServing {
|
||||
var requestStarted: ((Int) -> Void)?
|
||||
private var continuations: [CheckedContinuation<DroneDockPreparationResponse, Error>?] = []
|
||||
|
||||
/// 挂起当前请求,等待测试模拟后端回包。
|
||||
func workbench(scenicID: Int, orderNumber: String,
|
||||
coordinate: DroneDockPreparationCoordinate?) async throws -> DroneDockPreparationResponse {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
let index = continuations.count
|
||||
continuations.append(continuation)
|
||||
requestStarted?(index)
|
||||
}
|
||||
}
|
||||
|
||||
/// 完成指定请求一次,防止 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 cancelAll() {
|
||||
for index in continuations.indices { finish(index: index, result: .failure(CancellationError())) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user