Files
element-x-ios/Tools/Sources/Commands/CI/RunTests.swift
T
Mauro b1ed870474 Support for Xcode 27 on CI (#6217)
* Run the tests on iOS 27.0

Bump the required simulator OS in the preview, UI and Compound tests, and the CI tool's default OS, from 26.5 to 27.0. Test devices stay the same.

iOS 27 writes transcoded videos 146 bytes larger, so update the expected sizes in MediaUploadingPreprocessorTests.

* Build and test on CI with Xcode 27

Select Xcode 27 in ci_common.sh and move every macOS workflow to the xcode-27 runner image, as macos-26 doesn't include Xcode 27. The Compound workflow now also creates its simulator on the iOS 27.0 runtime.

The xcode-27 runners are slower, so give the unit, Enterprise, Compound and snapshot recording jobs longer timeouts.

* Fix the preview snapshot layout on iOS 27

On iOS 27 the hosting controller applies the window's safe area when rendering, but the snapshot size comes from sizeThatFits, which ignores it. Component previews were shifted down and clipped at the bottom. Disable the hosting controller's safe area regions for these snapshots so the measured and rendered layouts match.

swift-snapshot-testing also renders into a window without a scene, and on iOS 27 a navigation stack in such a window reserves space for a large title it never shows, leaving a gap below the navigation bar. Attach the render window to the app's scene until swift-snapshot-testing handles it.

The invite users and add rooms screens sized their selected items row from a measured width stored in state, which is zero on the first layout pass, so snapshots could draw the row empty. Use containerRelativeFrame instead. The add rooms search previews now also wait for their results, and the search previews that show a clear button get a small precision tolerance, as it renders inconsistently in snapshots.

* Re-record the preview snapshots on iOS 27.0

Recorded on an iPhone SE (3rd generation) simulator running iOS 27.0 with Xcode 27.0 (27A266a). The changes come from iOS 27 rendering: text anti-aliasing, hyphenation and line breaking, navigation bars and toggles that now render in snapshots, lazy stacks that were blank on iOS 26, and pseudo-language locale formatting.

* Fix the UI tests on iOS 27

iOS 27 no longer exposes accessibility identifiers on SwiftUI menu items, so the space exploration test now finds them by label within the menu. On iPad, the start chat search field keeps focus after submitting and can swallow the next tap, so retry the tap if the create room screen doesn't appear.

* Re-record the UI test snapshots on iOS 27.0

Recorded on iPhone 17 and iPad (A16) simulators running iOS 27.0 with Xcode 27.0. The changes come from iOS 27 styling, like the keyboard height and glass borders. This also removes the iPad app lock setup snapshots, which have been orphaned since those tests stopped running on iPad.

* Fix the accessibility tests crashing on iOS 27

The accessibility tests' previews wrapper kept its ImageRenderer alive across the awaits that follow the render. On iOS 27, releasing it at that point tears down its view graph outside of a SwiftUI update, which hits an assertion and crashes the app. Release the renderer as soon as the image has been rendered.

* Keep the accessibility tests' image renderers alive on iOS 27

Releasing the ImageRenderer straight away wasn't enough: on iOS 27, releasing one that rendered a preview crashes SwiftUI whichever context it happens in. Keep the renderers alive instead. Each test launches a fresh app, so they only live for the one test.

* Share the UI tests' app settings with their mock user session

Since the user session flow reads its settings from UserSettings, the UI tests' mock user session was wrapping a fresh volatile AppSettings instead of the one the tests configure. The flags that skip onboarding weren't picked up, so every user session UI test got stuck on the notifications permission screen.

* Re-record the Compound snapshots on iOS 27.0

Apply the same safe area fix as the app's preview tests, so size-that-fits snapshots aren't clipped on iOS 27, and re-record the snapshots on an iPhone SE (3rd generation) simulator running iOS 27.0 in English (US).

* Fix a race reading the keyboard in the accessibility tests

On iOS 27 the QR code login screen's keyboard can be dismissing between checking that it exists and reading its frame, which fails the test. Snapshot it in a single query instead.
2026-09-29 17:02:48 +02:00

167 lines
7.3 KiB
Swift

import ArgumentParser
import Foundation
struct RunTests: AsyncParsableCommand {
static let configuration = CommandConfiguration(abstract: "Runs xcodebuild tests with simulator management, retries, and formatting.",
discussion: """
Uses xcodebuild's native -retry-tests-on-failure flag to retry only \
failing tests instead of re-running the entire suite.
Examples:
swift run tools run-tests --scheme UnitTests
swift run tools run-tests --scheme UITests --device iPhone --os-version 27.0
swift run tools run-tests --scheme PreviewTests --create-simulator-name "iPhone SE (3rd generation)" \
--create-simulator-type com.apple.CoreSimulator.SimDeviceType.iPhone-SE-3rd-generation
""")
@Option(help: "The Xcode scheme to test.")
var scheme: String
@Option(help: "The simulator device name to run tests on (e.g. 'iPhone 17').")
var device = "iPhone 17"
@Option(help: "The iOS version to use for the simulator runtime (e.g. '27.0').")
var osVersion = CI.defaultOSVersion
var runtime: String {
osVersion.split(separator: ".").prefix(2).joined(separator: ".")
}
@Option(help: "Number of times to retry failed tests. Only the failing tests are re-run, not the entire suite.")
var retries = 0
@Option(help: "When set, create a simulator with this name if one doesn't already exist.")
var createSimulatorName: String?
@Option(help: "The simulator device type identifier for creating a new simulator (e.g. 'com.apple.CoreSimulator.SimDeviceType.iPhone-SE-3rd-generation').")
var createSimulatorType: String?
@Option(help: "Only run a specific test (format: 'ClassName/testName').")
var testName: String?
@Flag(help: "Run the tests on a saturated CPU to reproduce the flakiness of a busy CI runner.")
var constrained = false
private var isCI: Bool {
ProcessInfo.processInfo.environment["CI"] != nil
}
private var resultBundlePath: String {
"test_output/\(scheme).xcresult"
}
private var formatter: String {
"xcbeautify -q --disable-logging --is-ci --renderer github-actions"
}
private var simulatorRuntime: String {
"com.apple.CoreSimulator.SimRuntime.iOS-\(runtime.replacingOccurrences(of: ".", with: "-"))"
}
func run() async throws {
if let createName = createSimulatorName {
guard let createType = createSimulatorType else {
throw ValidationError("--create-simulator-type must be provided when --create-simulator-name is set.")
}
try await createSimulatorIfNecessary(name: createName, type: createType)
}
// Remove any previous result bundle at this path
let resultBundleURL = URL.projectDirectory.appendingPathComponent(resultBundlePath)
if FileManager.default.fileExists(atPath: resultBundleURL.path) {
try? FileManager.default.removeItem(at: resultBundleURL)
}
// Ensure the output directory exists
let outputDirectory = resultBundleURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
let cpuConstraint = CPUConstraint()
if constrained {
cpuConstraint.start()
}
defer { cpuConstraint.stop() }
try await executeXcodeBuild()
try await shutdownSimulator()
logger.info("\n✅ Tests passed.\n")
}
// MARK: - Simulator Management
private func createSimulatorIfNecessary(name: String, type: String) async throws {
logger.info("Checking for simulator '\(name)'…")
guard let simulators = try await CI.run(.path("/bin/zsh"), ["-cu", "xcrun simctl list devices \"iOS \(runtime)\" available"],
output: .string(limit: 4096)).standardOutput else {
logger.info("No simulators found for iOS \(runtime). Creating '\(name)'…")
try await createSimulator(name: name, type: type)
return
}
// Use a `(` to avoid matching e.g. "iPhone 14 Pro" on "iPhone 14 Pro Max"
let hasExisting = simulators.components(separatedBy: "\n").contains { line in
line.contains("\(name) (")
}
if hasExisting {
logger.info("Simulator '\(name)' already exists.")
} else {
logger.info("Simulator '\(name)' not found. Creating…")
try await createSimulator(name: name, type: type)
}
}
private func createSimulator(name: String, type: String) async throws {
let deviceID = try await CI.run(.path("/bin/zsh"), ["-cu", "xcrun simctl create '\(name)' \(type) \(simulatorRuntime)"],
output: .string(limit: 4096)).standardOutput
logger.info("Created simulator '\(name)' (\(deviceID?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "unknown")).")
}
// MARK: - Simulator Shutdown
private func shutdownSimulator() async throws {
print("Shutting down simulator '\(device)'…")
let command = "xcrun simctl shutdown '\(device)' 2>/dev/null || true"
try await CI.run(.path("/bin/zsh"), ["-cu", command])
print("Simulator shut down.")
}
// MARK: - Test Running
private func executeXcodeBuild() async throws {
var command = "set -o pipefail && xcodebuild test"
command += " -scheme \(scheme)"
command += " -destination 'platform=iOS Simulator,name=\(device),OS=\(osVersion),arch=arm64'"
command += " -resultBundlePath \(resultBundlePath)"
// Use a dedicated compilation cache for incremental builds on CI (as Xcode's DerivedData
// is invalidated by a fresh checkout).
command += " COMPILATION_CACHE_ENABLE_CACHING=YES"
// Store it outside DerivedData so CI can cache just what it needs.
command += " COMPILATION_CACHE_CAS_PATH=$HOME/Library/Developer/Xcode/CompilationCache.noindex"
// Use xcodebuild's native retry support to re-run only failing tests
// instead of re-running the entire suite. retries=0 means no retries (single run).
if retries > 0 {
// -test-iterations is the total number of attempts (initial + retries)
command += " -retry-tests-on-failure"
command += " -test-iterations \(retries + 1)"
// Ensure retries still happen when a runner exits early.
command += " -test-repetition-relaunch-enabled YES"
}
if let testName {
command += " -only-testing:\(scheme)/\(testName)"
}
command += " | \(formatter)"
try await CI.run(.path("/bin/zsh"), ["-cu", command])
}
}