import XCTest final class SurvivalTests: XCTestCase { @MainActor private func host(_ action: String) async throws -> Bool { let origin = ProcessInfo.processInfo.environment["SURVIVE_HOST"]! let (data, response) = try await URLSession.shared.data(from: URL(string: origin + "/" + action)!) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw NSError(domain: "SurvivalDriver", code: 1, userInfo: [NSLocalizedDescriptionKey: String(decoding: data, as: UTF8.self)]) } return (try JSONSerialization.jsonObject(with: data) as? [String: Bool])?["supported"] == true } @MainActor func testSurvival() async throws { let app = XCUIApplication(bundleIdentifier: ProcessInfo.processInfo.environment["SURVIVE_BUNDLE"]!) /// RULE: Activation must never hide a lifecycle crash by relaunching the app; check that it still runs before bringing it back. guard app.state != .notRunning else { XCTFail("app died before survive"); return } app.activate() try await Task.sleep(nanoseconds: 3_000_000_000) XCTAssertEqual(app.state, .runningForeground) /// RULE: Survival must prove a background state even on a headless simulator; a Home key can leave the app foreground and falsely skip the lifecycle that crashed build 269. let settings = XCUIApplication(bundleIdentifier: "com.apple.Preferences") for cycle in 1...2 { var locked = false var method = "activating com.apple.Preferences" if cycle == 2 { locked = try await host("lock") } if locked { method = "host power-key lock" } else { settings.activate() } try await Task.sleep(nanoseconds: 3_000_000_000) if locked && app.state == .runningForeground { print("survive: simulator power key cannot lock; backgrounding by activating com.apple.Preferences") locked = false method = "activating com.apple.Preferences after unsupported host power-key lock" settings.activate() try await Task.sleep(nanoseconds: 3_000_000_000) } let state = app.state print("survive: cycle \(cycle), \(method); state=\(state.rawValue)") XCTAssertTrue(state == .runningBackground || state == .runningBackgroundSuspended, "app must survive in the background after \(method) (cycle \(cycle)); state=\(state.rawValue)") guard state == .runningBackground || state == .runningBackgroundSuspended else { return } if locked { _ = try await host("unlock") } guard app.state != .notRunning else { XCTFail("app died before foregrounding"); return } app.activate() try await Task.sleep(nanoseconds: 3_000_000_000) XCTAssertEqual(app.state, .runningForeground, "app scene must return to the foreground") guard app.state == .runningForeground else { return } } } }