221 lines
13 KiB
Swift
221 lines
13 KiB
Swift
import UIKit
|
||
import XCTest
|
||
@testable import suixinkan
|
||
|
||
/// 使用可推进时钟和隔离读取验证逐秒显示、生命周期与后端状态切换,不连接真实设备。
|
||
@MainActor
|
||
final class DroneDockArrivalCountdownViewTests: XCTestCase {
|
||
/// 每秒只更新显示,到零不额外读取或开拍;后端明确拍摄中后才切换阶段。
|
||
func testCountdownOnlyUpdatesStartButtonAndWaitsForBackendShooting() async throws {
|
||
let fixture = try makeFixture()
|
||
defer { fixture.close() }
|
||
try await settle(fixture.window) { fixture.pulse.pendingCount == 1 }
|
||
let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton)
|
||
XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown"))
|
||
XCTAssertEqual(action.title(for: .normal), "开始拍摄(30s)")
|
||
XCTAssertTrue(action.isEnabled)
|
||
let initialFrame = action.convert(action.bounds, to: fixture.controller.view)
|
||
try await capture(fixture.window, action: action, expectedTitle: "开始拍摄(30s)", name: "App本地到达倒计时30秒(隔离替身)")
|
||
fixture.clock.advance(seconds: 1)
|
||
fixture.pulse.fire()
|
||
try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(29s)" && fixture.pulse.pendingCount == 1 }
|
||
XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action)
|
||
XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame)
|
||
fixture.clock.advance(seconds: 29.5)
|
||
fixture.pulse.fire()
|
||
try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(0s)" && fixture.pulse.pendingCount == 0 }
|
||
XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action)
|
||
XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame)
|
||
XCTAssertEqual(fixture.model.presentation.phase, .ready)
|
||
XCTAssertEqual(fixture.service.requests.count, 1)
|
||
XCTAssertEqual(fixture.start.count, 0, "本地倒数到零不能下发开拍")
|
||
XCTAssertTrue(action.isEnabled, "秒数不会改变后端开拍门禁")
|
||
try await capture(fixture.window, action: action, expectedTitle: "开始拍摄(0s)", name: "App本地倒计时0秒仍等待后端(隔离替身)")
|
||
fixture.service.result = .success(try snapshot(phase: "shooting", version: 2))
|
||
let item = try XCTUnwrap(fixture.controller.navigationItem.rightBarButtonItem)
|
||
_ = UIApplication.shared.sendAction(try XCTUnwrap(item.action), to: item.target, from: item, for: nil)
|
||
try await settle(fixture.window) { fixture.model.presentation.phase == .shooting }
|
||
XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown"))
|
||
XCTAssertFalse(action.currentTitle?.contains("s)") == true, "后端拍摄中必须清除旧倒计时文案")
|
||
XCTAssertNil(fixture.model.countdownRemainingSeconds)
|
||
XCTAssertEqual(fixture.service.requests.count, 2)
|
||
XCTAssertEqual(fixture.start.count, 0)
|
||
XCTAssertEqual(fixture.pulse.pendingCount, 0)
|
||
}
|
||
|
||
/// 手动开拍与本地数字显示并行,30秒、倒数中和0秒均可点,连点仍只提交一次。
|
||
func testManualStartRemainsTappableThroughoutCountdown() async throws {
|
||
for elapsed in [0.0, 12.0, 30.0] {
|
||
let fixture = try makeFixture()
|
||
defer { fixture.close() }
|
||
try await settle(fixture.window) { fixture.pulse.pendingCount == 1 }
|
||
let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton)
|
||
if elapsed > 0 {
|
||
fixture.clock.advance(seconds: elapsed)
|
||
fixture.pulse.fire()
|
||
try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(\(30 - Int(elapsed))s)" }
|
||
}
|
||
XCTAssertEqual(action.title(for: .normal), "开始拍摄(\(30 - Int(elapsed))s)")
|
||
XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown"))
|
||
XCTAssertTrue(action.isEnabled)
|
||
let center = action.convert(CGPoint(x: action.bounds.midX, y: action.bounds.midY), to: fixture.controller.view)
|
||
let hit = fixture.controller.view.hitTest(center, with: nil)
|
||
XCTAssertTrue(hit === action || hit?.isDescendant(of: action) == true)
|
||
XCTAssertEqual(fixture.start.count, 0)
|
||
action.sendActions(for: .touchUpInside)
|
||
action.sendActions(for: .touchUpInside)
|
||
try await settle(fixture.window) { fixture.start.count == 1 && !fixture.model.isStartingShooting }
|
||
XCTAssertTrue(fixture.model.startOutcomeUnknown, "隔离替身返回超时类错误,不能自动再次开拍")
|
||
XCTAssertEqual(fixture.service.requests.count, 1, "本地倒计时与未知开拍结果不额外触发读取")
|
||
XCTAssertEqual(fixture.model.presentation.phase, .ready, "受理或提交本身不替代后端拍摄中状态")
|
||
}
|
||
}
|
||
|
||
/// 后台与离页取消定时刷新;同任务批次返回后按已经过去的时间继续,不再从30开始。
|
||
func testBackgroundAndPageReentryPreserveElapsedTimeAndCancelTicks() async throws {
|
||
let fixture = try makeFixture()
|
||
defer { fixture.close() }
|
||
try await settle(fixture.window) { fixture.pulse.pendingCount == 1 }
|
||
let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton)
|
||
let initialFrame = action.convert(action.bounds, to: fixture.controller.view)
|
||
fixture.clock.advance(seconds: 8)
|
||
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||
try await settle(fixture.window) { fixture.pulse.pendingCount == 0 }
|
||
XCTAssertEqual(fixture.model.countdownRemainingSeconds, 22)
|
||
fixture.clock.advance(seconds: 12)
|
||
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||
try await settle(fixture.window) { fixture.service.requests.count == 2 && action.title(for: .normal) == "开始拍摄(10s)" && fixture.pulse.pendingCount == 1 }
|
||
fixture.controller.viewWillDisappear(false)
|
||
try await settle(fixture.window) { fixture.pulse.pendingCount == 0 }
|
||
fixture.clock.advance(seconds: 15)
|
||
fixture.controller.viewDidAppear(false)
|
||
try await settle(fixture.window) { fixture.service.requests.count == 3 && action.title(for: .normal) == "开始拍摄(0s)" }
|
||
XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action)
|
||
XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame)
|
||
XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown"))
|
||
XCTAssertEqual(fixture.pulse.pendingCount, 0)
|
||
XCTAssertEqual(fixture.start.count, 0)
|
||
XCTAssertEqual(fixture.model.presentation.phase, .ready)
|
||
}
|
||
|
||
private func makeFixture() throws -> CountdownPageFixture {
|
||
let context = DroneDockShootingTaskTestData.context()
|
||
let clock = DroneDockCountdownTestClock()
|
||
let service = DroneDockShootingTaskTestService(result: .success(try snapshot(phase: "arrived_pending_start", version: 1)))
|
||
let start = CountdownPageStartProbe()
|
||
let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501,
|
||
order: DroneDockShootingTaskTestData.order(), service: service, startService: start,
|
||
countdownNow: { clock.now() }, currentContext: { context })
|
||
let pulse = CountdownPagePulse()
|
||
let controller = DroneDockShootingTaskViewController(viewModel: model,
|
||
shootingPollDelay: { _ in try await Task.sleep(for: .seconds(3600)) }, countdownDelay: { try await pulse.wait() })
|
||
let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
|
||
let previous = scene?.windows.first { $0.isKeyWindow }
|
||
let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds)
|
||
window.rootViewController = UINavigationController(rootViewController: controller)
|
||
window.makeKeyAndVisible()
|
||
return CountdownPageFixture(controller: controller, window: window, previous: previous, model: model,
|
||
service: service, clock: clock, pulse: pulse, start: start)
|
||
}
|
||
|
||
private func snapshot(phase: String, version: Int) throws -> DroneDockShootingResponse {
|
||
try DroneDockShootingTaskTestData.response(changes: [
|
||
"task": ["id": 501, "status": 20], "order_flight_task": ["id": 501, "status": 20],
|
||
"execution_batch": 100, "state_version": version, "snapshot_kind": "full",
|
||
"flight_control": DroneDockShootingTaskTestData.flightControl(batch: 100, resumePhase: phase,
|
||
pauseReason: phase == "arrived_pending_start" ? "arrival_wait" : nil),
|
||
"ui": ["phase": phase, "title": phase == "shooting" ? "正在拍摄" : "无人机已到达",
|
||
"message": "本地模拟:未连接真实设备"],
|
||
"execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": "start_shoot"]
|
||
])
|
||
}
|
||
|
||
private func find(in root: UIView, id: String) -> UIView? {
|
||
if root.accessibilityIdentifier == id { return root }
|
||
return root.subviews.lazy.compactMap { self.find(in: $0, id: id) }.first
|
||
}
|
||
|
||
private func settle(_ window: UIWindow, until predicate: () -> Bool) async throws {
|
||
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||
while ContinuousClock.now < deadline {
|
||
window.layoutIfNeeded()
|
||
if predicate() { return }
|
||
try await Task.sleep(for: .milliseconds(10))
|
||
}
|
||
XCTFail("本地倒计时页面未达到预期状态")
|
||
throw NSError(domain: "CountdownPage", code: 1)
|
||
}
|
||
|
||
private func capture(_ window: UIWindow, action: UIButton, expectedTitle: String, name: String) async throws {
|
||
try await Task.sleep(for: .milliseconds(300))
|
||
window.layoutIfNeeded()
|
||
let label = try XCTUnwrap(action.titleLabel)
|
||
XCTAssertEqual(label.text, expectedTitle, "按钮实际渲染文字包含完整剩余秒数")
|
||
let textSize = (expectedTitle as NSString).size(withAttributes: [.font: label.font as Any])
|
||
XCTAssertGreaterThanOrEqual(label.bounds.width + 1, ceil(textSize.width), "按钮标题不能裁切秒数")
|
||
XCTAssertGreaterThanOrEqual(action.bounds.height, 44)
|
||
let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
|
||
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
|
||
})
|
||
attachment.name = name
|
||
attachment.lifetime = .keepAlways
|
||
add(attachment)
|
||
}
|
||
}
|
||
|
||
/// 持有单页隔离依赖并恢复测试前的窗口,避免通知或计时任务影响其他用例。
|
||
@MainActor
|
||
private struct CountdownPageFixture {
|
||
let controller: DroneDockShootingTaskViewController
|
||
let window: UIWindow
|
||
let previous: UIWindow?
|
||
let model: DroneDockShootingTaskViewModel
|
||
let service: DroneDockShootingTaskTestService
|
||
let clock: DroneDockCountdownTestClock
|
||
let pulse: CountdownPagePulse
|
||
let start: CountdownPageStartProbe
|
||
|
||
func close() {
|
||
controller.viewWillDisappear(false)
|
||
window.isHidden = true
|
||
window.rootViewController = nil
|
||
previous?.makeKeyAndVisible()
|
||
}
|
||
}
|
||
|
||
/// 由测试主动唤醒的本地逐秒刷新等待器,取消时立即释放 continuation。
|
||
@MainActor
|
||
private final class CountdownPagePulse {
|
||
private var pending: [(UUID, CheckedContinuation<Void, Error>)] = []
|
||
var pendingCount: Int { pending.count }
|
||
|
||
func wait() async throws {
|
||
let id = UUID()
|
||
try Task.checkCancellation()
|
||
try await withTaskCancellationHandler {
|
||
try await withCheckedThrowingContinuation { pending.append((id, $0)) }
|
||
} onCancel: {
|
||
Task { @MainActor in
|
||
guard let index = self.pending.firstIndex(where: { $0.0 == id }) else { return }
|
||
self.pending.remove(at: index).1.resume(throwing: CancellationError())
|
||
}
|
||
}
|
||
}
|
||
|
||
func fire() {
|
||
guard !pending.isEmpty else { return }
|
||
pending.removeFirst().1.resume()
|
||
}
|
||
}
|
||
|
||
/// 记录意外开拍调用,只返回本地错误,不创建网络传输。
|
||
@MainActor
|
||
private final class CountdownPageStartProbe: DroneDockStartShooting {
|
||
private(set) var count = 0
|
||
|
||
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse {
|
||
count += 1
|
||
throw APIError.networkFailed("本地模拟:不应自动开拍")
|
||
}
|
||
}
|