|
| 1 | +// |
| 2 | +// SnapshotHelper.swift |
| 3 | +// Example |
| 4 | +// |
| 5 | +// Created by Felix Krause on 10/8/15. |
| 6 | +// |
| 7 | + |
| 8 | +// ----------------------------------------------------- |
| 9 | +// IMPORTANT: When modifying this file, make sure to |
| 10 | +// increment the version number at the very |
| 11 | +// bottom of the file to notify users about |
| 12 | +// the new SnapshotHelper.swift |
| 13 | +// ----------------------------------------------------- |
| 14 | + |
| 15 | +import Foundation |
| 16 | +import XCTest |
| 17 | + |
| 18 | +var deviceLanguage = "" |
| 19 | +var locale = "" |
| 20 | + |
| 21 | +func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { |
| 22 | + Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) |
| 23 | +} |
| 24 | + |
| 25 | +func snapshot(_ name: String, waitForLoadingIndicator: Bool) { |
| 26 | + if waitForLoadingIndicator { |
| 27 | + Snapshot.snapshot(name) |
| 28 | + } else { |
| 29 | + Snapshot.snapshot(name, timeWaitingForIdle: 0) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/// - Parameters: |
| 34 | +/// - name: The name of the snapshot |
| 35 | +/// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. |
| 36 | +func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { |
| 37 | + Snapshot.snapshot(name, timeWaitingForIdle: timeout) |
| 38 | +} |
| 39 | + |
| 40 | +enum SnapshotError: Error, CustomDebugStringConvertible { |
| 41 | + case cannotDetectUser |
| 42 | + case cannotFindHomeDirectory |
| 43 | + case cannotFindSimulatorHomeDirectory |
| 44 | + case cannotAccessSimulatorHomeDirectory(String) |
| 45 | + case cannotRunOnPhysicalDevice |
| 46 | + |
| 47 | + var debugDescription: String { |
| 48 | + switch self { |
| 49 | + case .cannotDetectUser: |
| 50 | + return "Couldn't find Snapshot configuration files - can't detect current user " |
| 51 | + case .cannotFindHomeDirectory: |
| 52 | + return "Couldn't find Snapshot configuration files - can't detect `Users` dir" |
| 53 | + case .cannotFindSimulatorHomeDirectory: |
| 54 | + return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." |
| 55 | + case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): |
| 56 | + return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" |
| 57 | + case .cannotRunOnPhysicalDevice: |
| 58 | + return "Can't use Snapshot on a physical device." |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +@objcMembers |
| 64 | +open class Snapshot: NSObject { |
| 65 | + static var app: XCUIApplication? |
| 66 | + static var waitForAnimations = true |
| 67 | + static var cacheDirectory: URL? |
| 68 | + static var screenshotsDirectory: URL? { |
| 69 | + return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) |
| 70 | + } |
| 71 | + |
| 72 | + open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { |
| 73 | + |
| 74 | + Snapshot.app = app |
| 75 | + Snapshot.waitForAnimations = waitForAnimations |
| 76 | + |
| 77 | + do { |
| 78 | + let cacheDir = try pathPrefix() |
| 79 | + Snapshot.cacheDirectory = cacheDir |
| 80 | + setLanguage(app) |
| 81 | + setLocale(app) |
| 82 | + setLaunchArguments(app) |
| 83 | + } catch let error { |
| 84 | + NSLog(error.localizedDescription) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + class func setLanguage(_ app: XCUIApplication) { |
| 89 | + guard let cacheDirectory = self.cacheDirectory else { |
| 90 | + NSLog("CacheDirectory is not set - probably running on a physical device?") |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + let path = cacheDirectory.appendingPathComponent("language.txt") |
| 95 | + |
| 96 | + do { |
| 97 | + let trimCharacterSet = CharacterSet.whitespacesAndNewlines |
| 98 | + deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) |
| 99 | + app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] |
| 100 | + } catch { |
| 101 | + NSLog("Couldn't detect/set language...") |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + class func setLocale(_ app: XCUIApplication) { |
| 106 | + guard let cacheDirectory = self.cacheDirectory else { |
| 107 | + NSLog("CacheDirectory is not set - probably running on a physical device?") |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + let path = cacheDirectory.appendingPathComponent("locale.txt") |
| 112 | + |
| 113 | + do { |
| 114 | + let trimCharacterSet = CharacterSet.whitespacesAndNewlines |
| 115 | + locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) |
| 116 | + } catch { |
| 117 | + NSLog("Couldn't detect/set locale...") |
| 118 | + } |
| 119 | + |
| 120 | + if locale.isEmpty && !deviceLanguage.isEmpty { |
| 121 | + locale = Locale(identifier: deviceLanguage).identifier |
| 122 | + } |
| 123 | + |
| 124 | + if !locale.isEmpty { |
| 125 | + app.launchArguments += ["-AppleLocale", "\"\(locale)\""] |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + class func setLaunchArguments(_ app: XCUIApplication) { |
| 130 | + guard let cacheDirectory = self.cacheDirectory else { |
| 131 | + NSLog("CacheDirectory is not set - probably running on a physical device?") |
| 132 | + return |
| 133 | + } |
| 134 | + |
| 135 | + let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") |
| 136 | + app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] |
| 137 | + |
| 138 | + do { |
| 139 | + let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) |
| 140 | + let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) |
| 141 | + let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) |
| 142 | + let results = matches.map { result -> String in |
| 143 | + (launchArguments as NSString).substring(with: result.range) |
| 144 | + } |
| 145 | + app.launchArguments += results |
| 146 | + } catch { |
| 147 | + NSLog("Couldn't detect/set launch_arguments...") |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { |
| 152 | + if timeout > 0 { |
| 153 | + waitForLoadingIndicatorToDisappear(within: timeout) |
| 154 | + } |
| 155 | + |
| 156 | + NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work |
| 157 | + |
| 158 | + if Snapshot.waitForAnimations { |
| 159 | + sleep(1) // Waiting for the animation to be finished (kind of) |
| 160 | + } |
| 161 | + |
| 162 | + #if os(OSX) |
| 163 | + guard let app = self.app else { |
| 164 | + NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") |
| 165 | + return |
| 166 | + } |
| 167 | + |
| 168 | + app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) |
| 169 | + #else |
| 170 | + |
| 171 | + guard let app = self.app else { |
| 172 | + NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") |
| 173 | + return |
| 174 | + } |
| 175 | + |
| 176 | + let window = app.windows.firstMatch |
| 177 | + let screenshot = window.screenshot() |
| 178 | + guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } |
| 179 | + let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") |
| 180 | + do { |
| 181 | + try screenshot.pngRepresentation.write(to: path) |
| 182 | + } catch let error { |
| 183 | + NSLog("Problem writing screenshot: \(name) to \(path)") |
| 184 | + NSLog(error.localizedDescription) |
| 185 | + } |
| 186 | + #endif |
| 187 | + } |
| 188 | + |
| 189 | + class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { |
| 190 | + #if os(tvOS) |
| 191 | + return |
| 192 | + #endif |
| 193 | + |
| 194 | + guard let app = self.app else { |
| 195 | + NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") |
| 196 | + return |
| 197 | + } |
| 198 | + |
| 199 | + let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element |
| 200 | + let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) |
| 201 | + _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) |
| 202 | + } |
| 203 | + |
| 204 | + class func pathPrefix() throws -> URL? { |
| 205 | + let homeDir: URL |
| 206 | + // on OSX config is stored in /Users/<username>/Library |
| 207 | + // and on iOS/tvOS/WatchOS it's in simulator's home dir |
| 208 | + #if os(OSX) |
| 209 | + guard let user = ProcessInfo().environment["USER"] else { |
| 210 | + throw SnapshotError.cannotDetectUser |
| 211 | + } |
| 212 | + |
| 213 | + guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { |
| 214 | + throw SnapshotError.cannotFindHomeDirectory |
| 215 | + } |
| 216 | + |
| 217 | + homeDir = usersDir.appendingPathComponent(user) |
| 218 | + #else |
| 219 | + #if arch(i386) || arch(x86_64) |
| 220 | + guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { |
| 221 | + throw SnapshotError.cannotFindSimulatorHomeDirectory |
| 222 | + } |
| 223 | + guard let homeDirUrl = URL(string: simulatorHostHome) else { |
| 224 | + throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) |
| 225 | + } |
| 226 | + homeDir = URL(fileURLWithPath: homeDirUrl.path) |
| 227 | + #else |
| 228 | + throw SnapshotError.cannotRunOnPhysicalDevice |
| 229 | + #endif |
| 230 | + #endif |
| 231 | + return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +private extension XCUIElementAttributes { |
| 236 | + var isNetworkLoadingIndicator: Bool { |
| 237 | + if hasWhiteListedIdentifier { return false } |
| 238 | + |
| 239 | + let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) |
| 240 | + let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) |
| 241 | + |
| 242 | + return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize |
| 243 | + } |
| 244 | + |
| 245 | + var hasWhiteListedIdentifier: Bool { |
| 246 | + let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] |
| 247 | + |
| 248 | + return whiteListedIdentifiers.contains(identifier) |
| 249 | + } |
| 250 | + |
| 251 | + func isStatusBar(_ deviceWidth: CGFloat) -> Bool { |
| 252 | + if elementType == .statusBar { return true } |
| 253 | + guard frame.origin == .zero else { return false } |
| 254 | + |
| 255 | + let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) |
| 256 | + let newStatusBarSize = CGSize(width: deviceWidth, height: 44) |
| 257 | + |
| 258 | + return [oldStatusBarSize, newStatusBarSize].contains(frame.size) |
| 259 | + } |
| 260 | +} |
| 261 | + |
| 262 | +private extension XCUIElementQuery { |
| 263 | + var networkLoadingIndicators: XCUIElementQuery { |
| 264 | + let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in |
| 265 | + guard let element = evaluatedObject as? XCUIElementAttributes else { return false } |
| 266 | + |
| 267 | + return element.isNetworkLoadingIndicator |
| 268 | + } |
| 269 | + |
| 270 | + return self.containing(isNetworkLoadingIndicator) |
| 271 | + } |
| 272 | + |
| 273 | + var deviceStatusBars: XCUIElementQuery { |
| 274 | + guard let app = Snapshot.app else { |
| 275 | + fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") |
| 276 | + } |
| 277 | + |
| 278 | + let deviceWidth = app.windows.firstMatch.frame.width |
| 279 | + |
| 280 | + let isStatusBar = NSPredicate { (evaluatedObject, _) in |
| 281 | + guard let element = evaluatedObject as? XCUIElementAttributes else { return false } |
| 282 | + |
| 283 | + return element.isStatusBar(deviceWidth) |
| 284 | + } |
| 285 | + |
| 286 | + return self.containing(isStatusBar) |
| 287 | + } |
| 288 | +} |
| 289 | + |
| 290 | +private extension CGFloat { |
| 291 | + func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { |
| 292 | + return numberA...numberB ~= self |
| 293 | + } |
| 294 | +} |
| 295 | + |
| 296 | +// Please don't remove the lines below |
| 297 | +// They are used to detect outdated configuration files |
| 298 | +// SnapshotHelperVersion [1.16] |
0 commit comments