feat(drone-dock): 添加安全控制接口本地模拟调试
接入 command 请求合同与底部暂停、继续、返航、取消返航交互;支持同任务单次回查、防重复提交及未知结果锁。保留真实指令禁飞拦截,补充隔离测试、模拟回执与截图。
This commit is contained in:
@@ -0,0 +1,208 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import suixinkan
|
||||
|
||||
/// 使用纯内存响应核验四类安全指令合同,不访问后端或真实设备。
|
||||
@MainActor
|
||||
final class DroneDockCommandAPITests: XCTestCase {
|
||||
/// 四种操作都只发一次带鉴权 POST,任务身份使用 id,不传飞机或机场标识。
|
||||
func testEachCommandSendsOnlyTaskIDAndCommand() async throws {
|
||||
for command in DroneDockSafetyCommand.allCases {
|
||||
let session = MockURLSession(responses: [try envelope(data: payload(command: command))])
|
||||
let client = APIClient(environment: .testing, session: session)
|
||||
client.bindAuthTokenProvider { "command-test-token" }
|
||||
let response = try await DroneDockCommandAPI(client: client).sendCommand(taskID: 501, command: command)
|
||||
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
let request = try XCTUnwrap(session.requests.first)
|
||||
XCTAssertEqual(request.httpMethod, "POST")
|
||||
XCTAssertEqual(request.url?.path, "/api/app/airport/command")
|
||||
XCTAssertNil(request.url?.query)
|
||||
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "command-test-token")
|
||||
let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any])
|
||||
XCTAssertEqual(Set(body.keys), ["id", "command"])
|
||||
XCTAssertEqual(body["id"] as? Int, 501)
|
||||
XCTAssertEqual(body["command"] as? String, command.rawValue)
|
||||
XCTAssertEqual(response.orderFlightTaskID, 501)
|
||||
XCTAssertEqual(response.command, command.rawValue)
|
||||
XCTAssertEqual(response.airportSN, "LOCAL-MOCK-AIRPORT-501")
|
||||
XCTAssertEqual(response.metrics.map(\.key), ["battery", "satellite"])
|
||||
}
|
||||
}
|
||||
|
||||
/// 无效任务 ID 与已经取消的操作在进入传输前终止。
|
||||
func testInvalidOrCancelledRequestNeverReachesTransport() async throws {
|
||||
let session = MockURLSession(responses: [])
|
||||
let api = DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
for taskID in [0, -1] {
|
||||
do {
|
||||
_ = try await api.sendCommand(taskID: taskID, command: .pause)
|
||||
XCTFail("无效任务 ID 不应提交")
|
||||
} catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) }
|
||||
}
|
||||
let pending = Task { @MainActor in try await api.sendCommand(taskID: 501, command: .returnHome) }
|
||||
pending.cancel()
|
||||
do {
|
||||
_ = try await pending.value
|
||||
XCTFail("已取消的指令不应提交")
|
||||
} catch is CancellationError {}
|
||||
XCTAssertTrue(session.requests.isEmpty)
|
||||
}
|
||||
|
||||
/// 业务拒绝不受 data 形状影响,不伪造成成功或自动重试。
|
||||
func testBusinessFailurePreservesBackendReasonWithoutRetry() async throws {
|
||||
for data: Any in [NSNull(), [:] as [String: Any], [] as [Any], payload()] {
|
||||
let session = MockURLSession(responses: [try envelope(data: data, code: 100099,
|
||||
message: "模拟:任务未锁定飞机,请先召唤无人机")])
|
||||
do {
|
||||
_ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
XCTFail("拒绝不能转换为成功")
|
||||
} catch let APIError.serverCode(code, message) {
|
||||
XCTAssertEqual(code, 100099)
|
||||
XCTAssertEqual(message, "模拟:任务未锁定飞机,请先召唤无人机")
|
||||
}
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// 网络超时只回报一次失败,不自动重复具有设备副作用的指令。
|
||||
func testTimeoutDoesNotAutomaticallyRetry() async throws {
|
||||
let session = MockURLSession(results: [.failure(URLError(.timedOut))])
|
||||
do {
|
||||
_ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .returnHome)
|
||||
XCTFail("超时不能伪造成功")
|
||||
} catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) }
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
|
||||
/// HTTP 失败不能因业务包裹恰为成功而转成受理回执。
|
||||
func testHTTPFailureDoesNotBecomeSuccess() async throws {
|
||||
let session = MockURLSession(responses: [try envelope(data: payload())], statusCode: 503)
|
||||
do {
|
||||
_ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
XCTFail("HTTP 失败不能算成功")
|
||||
} catch let APIError.httpStatus(code, _) { XCTAssertEqual(code, 503) }
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
|
||||
/// 错任务、无效身份和错误回显指令都拒绝,不将别的操作结果交给当前按钮。
|
||||
func testMismatchedIdentityAndEchoAreRejected() async throws {
|
||||
let changes: [[String: Any]] = [
|
||||
["order_flight_task_id": 502], ["order_flight_task_id": 0],
|
||||
["order_flight_task_id": -1], ["order_flight_task_id": "501"],
|
||||
["order_flight_task_id": true], ["order_flight_task_id": NSNull()],
|
||||
["command": "return_home"], ["command": "unknown"], ["command": NSNull()]
|
||||
]
|
||||
for change in changes {
|
||||
let session = MockURLSession(responses: [try envelope(data: payload().merging(change) { _, new in new })])
|
||||
do {
|
||||
_ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
XCTFail("错误任务或指令回显应拒绝")
|
||||
} catch let APIError.decodeFailed(message) { XCTAssertFalse(message.isEmpty) }
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// 空响应或缺少必需回显不能生成成功回执。
|
||||
func testMissingDataAndEchoAreRejected() async throws {
|
||||
let data: [Any] = [NSNull(), [:] as [String: Any], [] as [Any],
|
||||
["order_flight_task_id": 501], ["command": "flighttask_pause"]]
|
||||
for value in data {
|
||||
let session = MockURLSession(responses: [try envelope(data: value)])
|
||||
do {
|
||||
_ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
XCTFail("缺失回显不能算成功")
|
||||
} catch let error as APIError {
|
||||
switch error {
|
||||
case .emptyData, .decodeFailed: break
|
||||
default: XCTFail("应保留数据缺失或解析错误:\(error)")
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// dji_status 的字符串、数字、对象、数组和 null 均保留原始 JSON,不强行映射为飞行阶段。
|
||||
func testMixedDJIStatusAndUnknownFieldsArePreserved() async throws {
|
||||
let statuses: [Any] = ["paused", 3, false, ["phase": "running", "code": 20],
|
||||
[NSNull(), "pending"], NSNull()]
|
||||
for status in statuses {
|
||||
var data = payload()
|
||||
data["dji_status"] = status
|
||||
data["future"] = ["text": "001", "count": 0, "empty": NSNull()] as [String: Any]
|
||||
let session = MockURLSession(responses: [try envelope(data: data)])
|
||||
let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
let original = try JSONDecoder().decode(DroneDockHomeJSONValue.self,
|
||||
from: JSONSerialization.data(withJSONObject: data))
|
||||
let displayed = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: Data(response.dataJSON.utf8))
|
||||
XCTAssertEqual(displayed, original)
|
||||
if status is NSNull { XCTAssertNil(response.djiStatus) }
|
||||
else { XCTAssertNotNil(response.djiStatus) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 缺少非身份展示字段仍保留未知值,不阻断已经核对身份的回执。
|
||||
func testOptionalDisplayFieldsRemainUnknownWhenMissing() async throws {
|
||||
let session = MockURLSession(responses: [try envelope(data: ["order_flight_task_id": 501,
|
||||
"command": "flighttask_pause"])])
|
||||
let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session))
|
||||
.sendCommand(taskID: 501, command: .pause)
|
||||
XCTAssertNil(response.airportSN)
|
||||
XCTAssertNil(response.djiStatus)
|
||||
XCTAssertTrue(response.metrics.isEmpty)
|
||||
}
|
||||
|
||||
/// 未标记本地模拟的传输在测试和生产环境都接收不到四类指令。
|
||||
func testDebugPolicyBlocksEveryCommandBeforeOrdinaryTransport() async throws {
|
||||
for environment in [APIEnvironment.testing, .production] {
|
||||
let session = SafetyCommandTransportProbe()
|
||||
let api = DroneDockCommandAPI(client: APIClient(environment: environment, session: session))
|
||||
for command in DroneDockSafetyCommand.allCases {
|
||||
do {
|
||||
_ = try await api.sendCommand(taskID: 501, command: command)
|
||||
XCTFail("新增 API 不得绕过禁飞保护")
|
||||
} catch is DeviceCommandDebugBlockedError {}
|
||||
}
|
||||
XCTAssertEqual(session.requestCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端动作列表缺失保持未知;未知动作可展示原文但不成为本地指令枚举。
|
||||
func testShootingCommandsDecodeKnownAndUnknownEntries() throws {
|
||||
let ui = try JSONDecoder().decode(DroneDockShootingUI.self, from: Data(#"{"phase":"paused","commands":[{"command":"flighttask_recovery","label":"继续拍摄","sub":"恢复航线"},{"command":"future_control","label":"未来操作"}]}"#.utf8))
|
||||
XCTAssertEqual(ui.commands?.count, 2)
|
||||
XCTAssertEqual(ui.commands?.first?.command, DroneDockSafetyCommand.resume.rawValue)
|
||||
XCTAssertEqual(ui.commands?.first?.label, "继续拍摄")
|
||||
XCTAssertEqual(ui.commands?.first?.sub, "恢复航线")
|
||||
XCTAssertNil(DroneDockSafetyCommand(rawValue: try XCTUnwrap(ui.commands?.last?.command)))
|
||||
let missing = try JSONDecoder().decode(DroneDockShootingUI.self, from: Data(#"{"phase":"shooting"}"#.utf8))
|
||||
XCTAssertNil(missing.commands)
|
||||
XCTAssertNil(DroneDockShootingUI(phase: "shooting", title: nil, message: nil).commands)
|
||||
}
|
||||
|
||||
private func payload(command: DroneDockSafetyCommand = .pause) -> [String: Any] {
|
||||
["order_flight_task_id": 501, "command": command.rawValue, "airport_sn": "LOCAL-MOCK-AIRPORT-501",
|
||||
"dji_status": "paused", "metrics": [["key": "battery", "value": "95%"],
|
||||
["key": "satellite", "value": "36颗"]]]
|
||||
}
|
||||
|
||||
private func envelope(data: Any, code: Int = 100000, message: String = "local mock success") throws -> Data {
|
||||
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data])
|
||||
}
|
||||
}
|
||||
|
||||
/// 不具备模拟豁免且自身绝不联网的探针,用于证明请求在真实传输边界前终止。
|
||||
private final class SafetyCommandTransportProbe: URLSessionProtocol {
|
||||
private(set) var requestCount = 0
|
||||
|
||||
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
|
||||
requestCount += 1
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user