162 lines
8.9 KiB
Swift
162 lines
8.9 KiB
Swift
import Foundation
|
|
import XCTest
|
|
@testable import suixinkan
|
|
|
|
/// 使用隔离网络替身验证游客确认码的请求、响应与整单只读查询。
|
|
@MainActor
|
|
final class DroneDockConfirmationAPITests: XCTestCase {
|
|
private let number = "TEST-CONFIRM-ORDER"
|
|
private let imageAddress = "https://example.invalid/mini_qr/confirm.png"
|
|
|
|
/// 生成确认码只传景区和完整订单号,复用当前摄影师登录凭证。
|
|
func testCreateSendsDocumentedBodyAndToken() async throws {
|
|
let session = MockURLSession(responses: [try envelope(code())])
|
|
let client = APIClient(environment: .testing, session: session)
|
|
client.bindAuthTokenProvider { "confirmation-test-token" }
|
|
let result = try await DroneDockConfirmationAPI(client: client)
|
|
.createConfirmation(scenicID: 128, orderNumber: number)
|
|
let request = try XCTUnwrap(session.requests.first)
|
|
XCTAssertEqual(session.requests.count, 1)
|
|
XCTAssertEqual(request.httpMethod, "POST")
|
|
XCTAssertEqual(request.url?.path, "/api/yf-handset-app/photog/multi-plane/orders/confirm-code")
|
|
XCTAssertNil(request.url?.query)
|
|
XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "confirmation-test-token")
|
|
let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any])
|
|
XCTAssertEqual(Set(body.keys), ["scenic_id", "order_number"])
|
|
XCTAssertEqual(body["scenic_id"] as? Int, 128)
|
|
XCTAssertEqual(body["order_number"] as? String, number)
|
|
XCTAssertEqual(result.orderNumber, number)
|
|
XCTAssertEqual(result.confirmStatus, 1)
|
|
XCTAssertEqual(result.confirmURL, imageAddress)
|
|
XCTAssertEqual(result.imageURL.absoluteString, imageAddress)
|
|
}
|
|
|
|
/// 刷新只读订单摘要和任务,不生成确认记录、创建任务或向无人机发指令。
|
|
func testConfirmationReusesScopedReadOnlyQueries() async throws {
|
|
let detail: [String: Any] = ["order_number": number, "can_confirm": true, "confirm_status": 1,
|
|
"order_status": 20, "film_count": 0, "spot": []]
|
|
let tasks: [String: Any] = ["order_number": number, "total": 0, "list": []]
|
|
let session = MockURLSession(responses: [try envelope(detail), try envelope(tasks), try envelope(tasks)])
|
|
let api = DroneDockConfirmationAPI(client: APIClient(environment: .testing, session: session))
|
|
let result = try await api.detail(scenicID: 128, orderNumber: number)
|
|
_ = try await api.tasks(scenicID: 128, orderNumber: number, spotID: nil)
|
|
_ = try await api.tasks(scenicID: 128, orderNumber: number, spotID: 201)
|
|
XCTAssertEqual(result.order.canConfirm, true)
|
|
XCTAssertEqual(result.order.orderStatus, 20)
|
|
XCTAssertEqual(result.order.filmCount, 0)
|
|
XCTAssertEqual(session.requests.map { $0.url?.path }, [
|
|
"/api/yf-handset-app/photog/multi-plane/orders/detail",
|
|
"/api/yf-handset-app/photog/multi-plane/tasks",
|
|
"/api/yf-handset-app/photog/multi-plane/tasks"
|
|
])
|
|
for (index, request) in session.requests.enumerated() {
|
|
XCTAssertEqual(request.httpMethod, "GET")
|
|
XCTAssertNil(request.httpBody)
|
|
var expected = ["scenic_id": "128", "order_number": number]
|
|
if index == 2 { expected["scenic_spot_id"] = "201" }
|
|
XCTAssertEqual(try query(request), expected)
|
|
}
|
|
}
|
|
|
|
/// 无效页面范围在发送前拒绝,订单号不做截断或自动修正。
|
|
func testInvalidScopeNeverReachesNetwork() async {
|
|
let session = MockURLSession(responses: [])
|
|
let api = DroneDockConfirmationAPI(client: APIClient(environment: .testing, session: session))
|
|
for (scenicID, order) in [(0, number), (-1, number), (128, ""), (128, " \n"),
|
|
(128, " TEST"), (128, "TEST\nORDER"), (128, String(repeating: "T", count: 129))] {
|
|
await assertFailure { _ = try await api.createConfirmation(scenicID: scenicID, orderNumber: order) }
|
|
}
|
|
XCTAssertTrue(session.requests.isEmpty)
|
|
}
|
|
|
|
/// 后端拒绝原样展示;重试由页面发起,失败请求不自动冒充待确认成功。
|
|
func testBackendFailurePreservesMessageAndAllowsExplicitRetry() async throws {
|
|
let session = MockURLSession(responses: [
|
|
try TestJSON.errorEnvelope(code: 160001, msg: "确认码生成失败,请重试"), try envelope(code())
|
|
])
|
|
let api = DroneDockConfirmationAPI(client: APIClient(environment: .testing, session: session))
|
|
do {
|
|
_ = try await api.createConfirmation(scenicID: 128, orderNumber: number)
|
|
XCTFail("应保留后端拒绝")
|
|
} catch let APIError.serverCode(code, message) {
|
|
XCTAssertEqual(code, 160001)
|
|
XCTAssertEqual(message, "确认码生成失败,请重试")
|
|
}
|
|
XCTAssertEqual(session.requests.count, 1)
|
|
let result = try await api.createConfirmation(scenicID: 128, orderNumber: number)
|
|
XCTAssertEqual(result.confirmStatus, 1)
|
|
XCTAssertEqual(session.requests.count, 2)
|
|
}
|
|
|
|
/// 其他订单的确认码不能在当前订单展示。
|
|
func testMismatchedOrderResponseIsRejected() async throws {
|
|
var payload = code()
|
|
payload["order_number"] = "OTHER-ORDER"
|
|
let session = MockURLSession(responses: [try envelope(payload)])
|
|
let api = DroneDockConfirmationAPI(client: APIClient(environment: .testing, session: session))
|
|
await assertFailure { _ = try await api.createConfirmation(scenicID: 128, orderNumber: self.number) }
|
|
}
|
|
|
|
/// 状态兼容整数字符串,图片地址可带合法查询参数且保持原样。
|
|
func testCodeAcceptsStringStatusAndRemoteImageQuery() throws {
|
|
var payload = code()
|
|
payload["confirm_status"] = "1"
|
|
payload["confirm_url"] = "http://example.invalid/mini_qr/confirm.png?version=2"
|
|
let result = try decode(payload)
|
|
XCTAssertEqual(result.confirmStatus, 1)
|
|
XCTAssertEqual(result.imageURL.absoluteString, payload["confirm_url"] as? String)
|
|
}
|
|
|
|
/// 缺失、空值、错误类型或非待确认状态不能被当成有效确认邀请。
|
|
func testMalformedCodeAndUnexpectedStatusAreRejected() throws {
|
|
for key in ["order_number", "confirm_status", "confirm_url"] {
|
|
var missing = code(); missing.removeValue(forKey: key)
|
|
XCTAssertThrowsError(try decode(missing), key)
|
|
var null = code(); null[key] = NSNull()
|
|
XCTAssertThrowsError(try decode(null), key)
|
|
}
|
|
for status: Any in [0, 2, -1, true, "unknown", 1.5, [:] as [String: Any]] {
|
|
var value = code(); value["confirm_status"] = status
|
|
XCTAssertThrowsError(try decode(value))
|
|
}
|
|
for order: Any in ["", " \n", " TEST", "TEST\nORDER", 123, String(repeating: "T", count: 129)] {
|
|
var value = code(); value["order_number"] = order
|
|
XCTAssertThrowsError(try decode(value))
|
|
}
|
|
}
|
|
|
|
/// 只接受可远程加载的 HTTP(S) 地址,不接受本地路径、凭据或无主机的 URL。
|
|
func testInvalidImageAddressesAreRejected() throws {
|
|
for address in ["", "/tmp/confirm.png", "file:///tmp/confirm.png", "data:image/png;base64,abcd",
|
|
"ftp://example.invalid/confirm.png", "https:///confirm.png", "https://",
|
|
"https://user:password@example.invalid/confirm.png", "https://user@example.invalid/confirm.png",
|
|
" https://example.invalid/confirm.png", "https://example.invalid/confirm code.png",
|
|
"https://example.invalid/confirm\ncode.png", "https://example.invalid/" + String(repeating: "a", count: 2048)] {
|
|
var payload = code(); payload["confirm_url"] = address
|
|
XCTAssertThrowsError(try decode(payload), address)
|
|
}
|
|
}
|
|
|
|
private func code() -> [String: Any] {
|
|
["order_number": number, "confirm_status": 1, "confirm_url": imageAddress]
|
|
}
|
|
|
|
private func envelope(_ value: [String: Any]) throws -> Data {
|
|
try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": value])
|
|
}
|
|
|
|
private func decode(_ value: [String: Any]) throws -> DroneDockConfirmationCode {
|
|
try JSONDecoder().decode(DroneDockConfirmationCode.self, from: JSONSerialization.data(withJSONObject: value))
|
|
}
|
|
|
|
private func query(_ request: URLRequest) throws -> [String: String] {
|
|
let url = try XCTUnwrap(request.url)
|
|
let items = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false)).queryItems ?? []
|
|
return Dictionary(uniqueKeysWithValues: items.map { ($0.name, $0.value ?? "") })
|
|
}
|
|
|
|
private func assertFailure(_ action: () async throws -> Void, file: StaticString = #filePath, line: UInt = #line) async {
|
|
do { try await action(); XCTFail("应拒绝无效确认结果", file: file, line: line) } catch {}
|
|
}
|
|
}
|