feat: 统一机巢加载体验并对齐到达态界面

工作台、准备页、任务首次读取和景区空境库复用应用通用 Loading;到达态按 Web 展示,保留倒计时及手动开拍权限。新增图传几何诊断,不改变 Fit 渲染或设备连接行为。

验证:App 与测试包无签名 build-for-testing 编译通过,git diff --check 通过。iPhone 11 当前 unavailable,真机回归待设备重连后执行。
This commit is contained in:
2026-11-04 18:47:17 +08:00
parent b3fa6cf7d7
commit 3882a0d4c6
17 changed files with 906 additions and 16 deletions
@@ -0,0 +1,246 @@
import UIKit
import VolcEngineRTC
import XCTest
@testable import suixinkan
/// 图传几何诊断仅使用内存接收器和播放器,验证日志不能改变播放或网络行为。
@MainActor
final class DroneDockLiveGeometryTests: XCTestCase {
/// 帧宽高及旋转保留 SDK 原值,缺失信息为 null,便于与实际画布比例对照。
func testDiagnosticPayloadPreservesRawRotationAndUnknownFrame() throws {
let value = geometry(frame: .init(width: 720, height: 1280, rotation: 90))
let fields = value.diagnosticFields
XCTAssertEqual(fields["frame_w"] as? Int, 720)
XCTAssertEqual(fields["frame_h"] as? Int, 1280)
XCTAssertEqual(fields["rotation"] as? Int, 90)
XCTAssertEqual(fields["rotation_unit"] as? String, "degree")
XCTAssertEqual(fields["frame_unit"] as? String, "px")
XCTAssertEqual(fields["container_unit"] as? String, "pt")
XCTAssertEqual(fields["container_w"] as? Double, 390)
XCTAssertEqual(fields["container_h"] as? Double, 219.375)
XCTAssertEqual(fields["render_mode"] as? String, "fit")
XCTAssertTrue(JSONSerialization.isValidJSONObject(fields))
let unknown = geometry(frame: nil).diagnosticFields
for key in ["frame_w", "frame_h", "rotation", "sdk_version"] {
XCTAssertTrue(unknown[key] is NSNull, key)
}
XCTAssertTrue(JSONSerialization.isValidJSONObject(unknown))
}
/// 重复首帧及相同尺寸不重复输出,真正尺寸变化只更新诊断,不重新订阅或切流。
func testFirstFrameAndSizeChangesAreDeduplicatedWithoutChangingSubscriptions() async throws {
let engine = GeometryEngineProbe()
let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine })
let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375))
var geometries: [DroneDockLiveGeometry] = []
var playback: [DroneDockLivePlaybackEvent] = []
receiver.setGeometryHandler { geometries.append($0) }
receiver.start([configuration("airport")], in: view) { playback.append($0) }
defer { receiver.stop() }
let room = try XCTUnwrap(engine.rooms["airport-room"])
room.emit(.published("airport-stream", "airport-room", true))
await drain()
let frame = DroneDockVideoFrameGeometry(width: 1920, height: 1080, rotation: 0)
room.emit(.frame("airport-stream", "airport-room", frame))
await drain()
XCTAssertEqual(geometries.map(\.trigger), ["first_frame", "source_changed"])
let shown = try XCTUnwrap(geometries.last)
XCTAssertEqual(shown.role, "airport")
XCTAssertEqual(shown.roomID, "airport-room")
XCTAssertEqual(shown.streamID, "airport-stream")
XCTAssertEqual(shown.frame, frame)
XCTAssertEqual(shown.sdkVersion, "TEST-SDK")
XCTAssertEqual(shown.containerWidth, 390)
XCTAssertEqual(shown.containerHeight, 219.375)
XCTAssertEqual(shown.hostWidth, 390)
XCTAssertTrue(shown.isSelected)
for _ in 0..<5 {
room.emit(.frame("airport-stream", "airport-room", frame))
room.emit(.videoSizeChanged("airport-stream", "airport-room", frame))
}
await drain()
XCTAssertEqual(geometries.count, 2)
let rotated = DroneDockVideoFrameGeometry(width: 720, height: 1280, rotation: 90)
room.emit(.videoSizeChanged("airport-stream", "airport-room", rotated))
await drain()
XCTAssertEqual(geometries.last?.trigger, "video_size_changed")
XCTAssertEqual(geometries.last?.frame, rotated)
XCTAssertEqual(geometries.count, 3)
XCTAssertEqual(playback, [.sourceChanged("airport")])
XCTAssertEqual(room.subscriptions, ["airport-stream:true"])
XCTAssertEqual(engine.bindings, ["airport-stream"])
XCTAssertEqual(view.bounds.size, CGSize(width: 390, height: 219.375))
XCTAssertEqual(view.subviews.first?.bounds.size, view.bounds.size)
}
/// 尺寸回调不是首帧证据,不能提前开放另一房间或将页面变成正在播放。
func testSizeCallbackCannotStartPlaybackOrConnectSecondSource() async throws {
let engine = GeometryEngineProbe()
let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine })
let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375))
var geometries: [DroneDockLiveGeometry] = []
var playback: [DroneDockLivePlaybackEvent] = []
receiver.setGeometryHandler { geometries.append($0) }
receiver.start([configuration("airport"), configuration("drone")], in: view) { playback.append($0) }
defer { receiver.stop() }
let room = try XCTUnwrap(engine.rooms["airport-room"])
room.emit(.published("airport-stream", "airport-room", true))
await drain()
room.emit(.videoSizeChanged("airport-stream", "airport-room", .init(width: 1440, height: 1080, rotation: 0)))
await drain()
XCTAssertEqual(geometries.map(\.trigger), ["video_size_changed"])
XCTAssertFalse(try XCTUnwrap(geometries.first).isSelected)
XCTAssertTrue(playback.isEmpty)
XCTAssertNil(engine.rooms["drone-room"])
XCTAssertEqual(engine.bindings, ["airport-stream"])
}
/// 两路尺寸各自保存;错误身份和已释放会话的迟到回调不能污染日志,回退使用机巢尺寸。
func testSourceSwitchFallbackAndStaleIdentityKeepIndependentGeometry() async throws {
let engine = GeometryEngineProbe()
let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine })
let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 219.375))
var geometries: [DroneDockLiveGeometry] = []
receiver.setGeometryHandler { geometries.append($0) }
receiver.start([configuration("airport"), configuration("drone")], in: view) { _ in }
defer { receiver.stop() }
let airport = try XCTUnwrap(engine.rooms["airport-room"])
let airportFrame = DroneDockVideoFrameGeometry(width: 1920, height: 1080, rotation: 0)
airport.emit(.published("airport-stream", "airport-room", true))
await drain()
airport.emit(.frame("airport-stream", "airport-room", airportFrame))
await drain()
let drone = try XCTUnwrap(engine.rooms["drone-room"])
drone.emit(.published("drone-stream", "drone-room", true))
await drain()
let droneFrame = DroneDockVideoFrameGeometry(width: 1440, height: 1080, rotation: 0)
drone.emit(.frame("wrong-stream", "drone-room", droneFrame))
drone.emit(.videoSizeChanged("drone-stream", "wrong-room", droneFrame))
await drain()
XCTAssertEqual(geometries.count, 2)
drone.emit(.frame("drone-stream", "drone-room", droneFrame))
await drain()
XCTAssertEqual(geometries.last?.role, "drone")
XCTAssertEqual(geometries.last?.frame, droneFrame)
drone.emit(.videoState("drone-stream", "drone-room", .frozen))
await drain()
XCTAssertEqual(geometries.last?.trigger, "source_changed")
XCTAssertEqual(geometries.last?.role, "airport")
XCTAssertEqual(geometries.last?.frame, airportFrame)
receiver.stop()
let count = geometries.count
drone.emit(.frame("drone-stream", "drone-room", droneFrame))
airport.emit(.videoSizeChanged("airport-stream", "airport-room", droneFrame))
await drain()
XCTAssertEqual(geometries.count, count)
XCTAssertEqual(engine.destroyCount, 1)
}
/// 诊断回调沿用当前任务会话,离页和重新进入后的旧回调均被丢弃,不能触发播放或新请求。
func testViewForwardsOnlyCurrentSessionGeometryWithoutChangingPlayback() async throws {
let context = DroneDockShootingTaskTestData.context()
let service = GeometryParameterProbe(response: try DroneDockRTCFixture.response())
let model = DroneDockLiveViewModel(context: context, taskID: 501, service: service,
allowsDevicePlayback: true, now: { DroneDockRTCFixture.now }, currentContext: { context })
await model.refresh()
let player = GeometryPlayerProbe()
let view = DroneDockTaskLiveView(rtcPlayer: player)
var records: [[String: Any]] = []
view.onDiagnosticEvent = { event, fields in if event == "live.geometry" { records.append(fields) } }
view.apply(model)
view.setPlaybackActive(true)
let oldHandler = try XCTUnwrap(player.geometryHandler)
oldHandler(geometry(frame: .init(width: 1440, height: 1080, rotation: 0)))
XCTAssertEqual(records.count, 1)
XCTAssertEqual(records.first?["receiver_session"] as? String, model.playbackSessionID?.uuidString)
XCTAssertEqual(model.state, .connecting)
XCTAssertEqual(player.starts, 1)
XCTAssertEqual(service.calls, 1)
view.setPlaybackActive(false)
oldHandler(geometry(frame: nil))
XCTAssertEqual(records.count, 1)
XCTAssertNil(player.geometryHandler)
model.invalidate()
await model.refresh()
view.apply(model)
view.setPlaybackActive(true)
oldHandler(geometry(frame: nil))
XCTAssertEqual(records.count, 1)
try XCTUnwrap(player.geometryHandler)(geometry(frame: .init(width: 1920, height: 1080, rotation: 0)))
XCTAssertEqual(records.count, 2)
XCTAssertNotEqual(records.first?["receiver_session"] as? String, records.last?["receiver_session"] as? String)
XCTAssertEqual(model.state, .connecting)
XCTAssertEqual(player.starts, 2)
XCTAssertEqual(service.calls, 2)
view.setPlaybackActive(false)
}
/// 尺寸回调是 SDK optional Objective-C 方法,必须确实注册才能收到旋转或分辨率变化。
func testSDKSizeChangeDelegateSelectorIsRegistered() {
let delegate = DroneDockVolcDelegate { _ in }
XCTAssertTrue(delegate.responds(to: NSSelectorFromString("rtcEngine:onRemoteVideoSizeChanged:info:withFrameInfo:")))
}
private func configuration(_ role: String) -> DroneDockVolcLiveConfiguration {
.init(appID: "TEST", roomID: "\(role)-room", userID: "viewer", token: "TEST",
expiresAt: Date().addingTimeInterval(3600), role: role)
}
private func geometry(frame: DroneDockVideoFrameGeometry?) -> DroneDockLiveGeometry {
.init(trigger: "first_frame", role: "drone", roomID: "TEST-room", streamID: "TEST-stream", frame: frame,
containerWidth: 390, containerHeight: 219.375, hostWidth: 390, hostHeight: 219.375,
isSelected: true, sdkVersion: nil)
}
private func drain() async { for _ in 0..<20 { await Task.yield() } }
}
/// 无 SDK 引擎,只记录绑定与房间创建次数。
@MainActor
private final class GeometryEngineProbe: DroneDockRTCReceivingEngine {
let sdkVersion: String? = "TEST-SDK"
var rooms: [String: GeometryRoomProbe] = [:]
var bindings: [String] = []
var destroyCount = 0
func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? {
let room = GeometryRoomProbe(emit: onEvent)
rooms[id] = room
return room
}
func setVideoView(_ view: UIView?, streamID: String) -> Int { bindings.append(streamID); return 0 }
func destroy() { destroyCount += 1 }
}
/// 所有事件由测试主动发送,不访问网络或设备。
@MainActor
private final class GeometryRoomProbe: DroneDockRTCReceivingRoom {
let emit: @Sendable (DroneDockVolcEvent) -> Void
var subscriptions: [String] = []
init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit }
func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int { 0 }
func updateToken(_ token: String) -> Int { 0 }
func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int {
subscriptions.append("\(streamID):\(subscribe)"); return 0
}
func destroy() {}
}
/// 几何和播放回调分离的无网络播放器。
@MainActor
private final class GeometryPlayerProbe: DroneDockLivePlaying {
var starts = 0
var geometryHandler: (@MainActor (DroneDockLiveGeometry) -> Void)?
func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { geometryHandler = handler }
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { starts += 1 }
func stop() {}
}
/// 参数查询计数替身,验证诊断不会引入额外接口读取。
@MainActor
private final class GeometryParameterProbe: DroneDockLiveServing {
let response: DroneDockLiveResponse
var calls = 0
init(response: DroneDockLiveResponse) { self.response = response }
func live(taskID: Int) async throws -> DroneDockLiveResponse { calls += 1; return response }
}
@@ -9,6 +9,8 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
/// 设备请求尚未返回时先展示等高空卡片,返回设备后下方模块不跳动。
func testPendingDeviceRequestKeepsPlaceholderCardAtFullDeviceHeight() async throws {
GlobalLoadingManager.shared.hideAll()
defer { GlobalLoadingManager.shared.hideAll() }
let gate = HomeDeviceResponseGate()
defer { Task { await gate.release() } }
let (controller, session) = makeController(responses: [populatedEnvelope], deviceResponseGate: gate)
@@ -20,12 +22,15 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
try await settle(window: window) {
session.requests.count == 3 && controller.viewModel.isLoading
&& (collection.cellForItem(at: path) as? DroneDockDeviceCell)?.cardView.accessibilityIdentifier == "drone.device.empty"
&& GlobalLoadingManager.shared.isShowing
}
let placeholder = try XCTUnwrap((collection.cellForItem(at: path) as? DroneDockDeviceCell)?.cardView)
let frame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: path)).frame
XCTAssertEqual(collection.numberOfItems(inSection: 1), 1)
XCTAssertEqual(frame.height, 248, accuracy: 0.5)
XCTAssertNil(controller.viewModel.response)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
XCTAssertTrue(window.subviews.contains { $0 is GlobalLoadingOverlayView })
XCTAssertTrue(visibleTexts(in: placeholder).contains("暂无无人机"))
XCTAssertTrue(visibleTexts(in: placeholder).contains("正在加载"))
XCTAssertEqual(metricTexts(in: placeholder), Dictionary(uniqueKeysWithValues: metricKeys.map { ($0, "—") }))
@@ -37,6 +42,7 @@ final class DroneDockRemoteHomeViewTests: XCTestCase {
&& !collection.hasUncommittedUpdates
}
let loadedFrame = try XCTUnwrap(collection.collectionViewLayout.layoutAttributesForItem(at: path)).frame
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
XCTAssertEqual(loadedFrame.minY, frame.minY, accuracy: 0.5)
XCTAssertEqual(loadedFrame.height, frame.height, accuracy: 0.5)
assertOnlyReadHomepageRequests(session)
@@ -50,7 +50,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
XCTAssertFalse(visibleTexts(in: controller.view).contains("正在获取任务状态"))
service.finish()
try await settle(window) { controller.viewModel.presentation.phase == .ready }
XCTAssertTrue(visibleTexts(in: controller.view).contains("本地模拟:无人机已到达"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已到达"))
}
/// 使用模拟 WebSocket 推进任务阶段,断线立即 HTTP 兜底,恢复后停轮询;固定布局不变。
@@ -72,7 +72,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase {
socket.emit(try RealtimeTestData.push(XCTUnwrap(JSONSerialization.jsonObject(with: Data(ready.dataJSON.utf8)) as? [String: Any])))
try await settle(window) { controller.viewModel.response?.stateVersion == 2 && clock.pendingCount == 0 }
XCTAssertEqual(controller.viewModel.presentation.phase, .ready)
XCTAssertTrue(visibleTexts(in: controller.view).contains("本地模拟:无人机已到达"))
XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已到达"))
service.suspendNext = true
service.response = try realtimeViewSnapshot(version: 3, phase: "shooting", title: "本地模拟:正在拍摄")
socket.fail()
@@ -36,7 +36,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
let note = try XCTUnwrap(find(in: status, suffix: "failureNote") as? UILabel)
XCTAssertFalse(isHidden(note))
XCTAssertEqual(note.text, "无人机离线,暂不可召唤")
} else if [.shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) {
} else if [.ready, .shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) {
XCTAssertTrue(isHidden(device))
} else {
XCTAssertFalse(isHidden(device))
@@ -141,6 +141,91 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase {
}
}
/// 到达面板采用蓝色圆勾与三级文案,保留完整秒数、整行按钮和实际可点击区域。
func testReadyPanelMatchesPrototypeAndKeepsCountdownActionTappable() throws {
for size in [CGSize(width: 320, height: 146), compactSize, regularSize] {
let status = makeStatus(size: size)
let ready = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达",
message: "确认游客站位与取景后开始", deviceStatus: "设备摘要不应显示", action: .start,
actionTitle: "开始拍摄", isActionEnabled: true, countdownSeconds: 30)
apply(ready, to: status)
let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel)
let prompt = try XCTUnwrap(find(in: status, suffix: "readyPrompt") as? UILabel)
let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel)
let icon = try XCTUnwrap(find(in: status, suffix: "readyIcon"))
let button = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton)
XCTAssertEqual(title.text, "无人机已到达")
XCTAssertEqual(prompt.text, "是否开始拍摄?")
XCTAssertEqual(message.text, "确认游客站位与取景后开始")
XCTAssertFalse(isHidden(prompt))
XCTAssertFalse(isHidden(message))
XCTAssertEqual(icon.backgroundColor, UIColor(hex: 0xE2EDFF))
XCTAssertEqual((icon.subviews.first as? UIImageView)?.tintColor, UIColor(hex: 0x0671FF))
XCTAssertEqual(title.convert(title.bounds, to: status).minY, icon.convert(icon.bounds, to: status).minY, accuracy: 0.5)
XCTAssertEqual(title.convert(title.bounds, to: status).minX, prompt.convert(prompt.bounds, to: status).minX, accuracy: 0.5)
XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5)
XCTAssertGreaterThan(prompt.convert(prompt.bounds, to: status).minY, title.convert(title.bounds, to: status).maxY)
XCTAssertGreaterThan(message.convert(message.bounds, to: status).minY, prompt.convert(prompt.bounds, to: status).maxY)
XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus"))))
XCTAssertEqual(button.bounds.width, size.width - 36, accuracy: 0.5)
XCTAssertNotNil(button.configuration?.image)
var calls = 0
status.onPrimaryAction = { calls += 1 }
let initialFrame = button.convert(button.bounds, to: status)
for (index, seconds) in [30, 29, 0].enumerated() {
status.updateCountdown(seconds: seconds)
layoutHierarchy(status)
try assertFullButtonTitle("开始拍摄(\(seconds)s)", button: button)
XCTAssertTrue(button.isEnabled)
XCTAssertEqual(button.convert(button.bounds, to: status), initialFrame)
let center = button.convert(CGPoint(x: button.bounds.midX, y: button.bounds.midY), to: status)
let hit = status.hitTest(center, with: nil)
XCTAssertTrue(hit === button || hit?.isDescendant(of: button) == true)
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, index + 1)
}
try assertReadableContainedContent(in: status)
capture(status, name: "已到达-蓝色圆勾三级文案-\(Int(size.width))x\(Int(size.height))")
status.apply(ready, isPrimaryActionLoading: true)
layoutHierarchy(status)
let spinner = try XCTUnwrap(find(in: status, suffix: "primary.loading") as? UIActivityIndicatorView)
XCTAssertTrue(spinner.isAnimating)
XCTAssertFalse(button.isEnabled)
XCTAssertEqual(title.text, "无人机已到达")
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 3)
status.updateCountdown(seconds: 0)
XCTAssertFalse(button.isEnabled, "倒计时不能覆盖提交中的操作保护")
status.apply(ready)
layoutHierarchy(status)
XCTAssertFalse(spinner.isAnimating)
XCTAssertTrue(button.isEnabled)
}
}
/// 开拍结果待核对时继续显示原始说明和刷新动作,不误显示可开拍的倒计时。
func testReadyPanelPreservesOutcomeMessageAndRefreshAction() throws {
let status = makeStatus(size: regularSize)
let value = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达",
message: "操作结果未知,请刷新核对任务状态。", deviceStatus: "拍摄中", action: .refresh,
actionTitle: "刷新状态", isActionEnabled: true, countdownSeconds: 30)
apply(value, to: status)
let button = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton)
XCTAssertEqual((find(in: status, suffix: "statusMessage") as? UILabel)?.text, value.message)
XCTAssertEqual(button.title(for: .normal), "刷新状态")
XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden")
var calls = 0
status.onPrimaryAction = { calls += 1 }
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 1)
status.apply(value, isRefreshing: true)
button.sendActions(for: .touchUpInside)
XCTAssertEqual(calls, 1)
XCTAssertFalse(button.isEnabled)
try assertReadableContainedContent(in: status)
}
/// 从到达到拍摄中再进入错误/完成状态时,独立面板和通用操作互不留下旧入口。
func testShootingPanelTransitionsClearOldCountdownAndRestoreAllowedAction() throws {
let status = makeStatus(size: regularSize)
@@ -0,0 +1,90 @@
import UIKit
import XCTest
@testable import suixinkan
/// 页面通用 Loading 必须跟随可见性,并与其它页面或请求的令牌相互独立。
@MainActor
final class GlobalPageLoadingTests: XCTestCase {
override func setUp() {
super.setUp()
GlobalLoadingManager.shared.hideAll()
}
override func tearDown() {
GlobalLoadingManager.shared.hideAll()
super.tearDown()
}
/// 页面首次读取可以提前标记,但只有完整出现后才使用通用遮罩。
func testLoadingWaitsForVisiblePageAndFinishesWithoutLeaking() {
let controller = makeController()
controller.setPageLoading(true)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
controller.viewDidAppear(false)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
controller.setPageLoading(false)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
controller.viewWillDisappear(false)
}
/// 同步重复刷新展示不会重复持有令牌,成功或错误结束都只需一次释放。
func testRepeatedLoadingUpdatesOwnOnlyOneToken() {
let controller = makeController()
controller.viewDidAppear(false)
controller.setPageLoading(true)
controller.setPageLoading(true)
controller.setPageLoading(true)
controller.setPageLoading(false)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
controller.viewWillDisappear(false)
}
/// 离页时释放本页;迟到的结束不能关闭另一请求,迟到开始也不能覆盖新页面。
func testLeavingAndLateUpdatesCannotHideOrCoverAnotherPage() {
let controller = makeController()
controller.viewDidAppear(false)
controller.setPageLoading(true)
let other = GlobalLoadingManager.shared.beginRequest()
controller.viewWillDisappear(false)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
controller.setPageLoading(false)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
GlobalLoadingManager.shared.endRequest(other)
controller.setPageLoading(true)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
}
/// 后台关闭通用遮罩,返回前台只恢复仍可见且读取未结束的页面。
func testBackgroundAndForegroundRespectPendingReadAndVisibility() {
let controller = makeController()
controller.viewDidAppear(false)
controller.setPageLoading(true)
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
GlobalLoadingManager.shared.hideAll()
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
controller.viewWillDisappear(false)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
}
/// 请求已在后台完成时,不因页面回到前台而重新展示过期遮罩。
func testReadFinishingInBackgroundDoesNotRestoreLoading() {
let controller = makeController()
controller.viewDidAppear(false)
controller.setPageLoading(true)
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
controller.setPageLoading(false)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
controller.viewWillDisappear(false)
}
private func makeController() -> GlobalLoadingPageViewController {
let controller = GlobalLoadingPageViewController()
controller.loadViewIfNeeded()
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
return controller
}
}