Skip to content

Commit

Permalink
Updates to screenshot generation
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewBennet committed Sep 27, 2020
1 parent 639dd92 commit 0e871c2
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 120 deletions.
40 changes: 20 additions & 20 deletions Debug/examplebooks.csv

Large diffs are not rendered by default.

22 changes: 16 additions & 6 deletions ReadingList/Startup/LaunchManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ class LaunchManager {
return true
}

var presentFirstLaunchOrChangeLog: Bool {
#if DEBUG
return !CommandLine.arguments.contains("--UITests_Screenshots")
#else
return true
#endif
}

private func initialiseAfterPersistentStoreLoad() {
#if DEBUG
Debug.initialiseData()
Expand All @@ -175,12 +183,14 @@ class LaunchManager {
NotificationCenter.default.addObserver(self, selector: #selector(self.initialiseTheme), name: .ThemeSettingChanged, object: nil)
}

if isFirstLaunch {
let firstOpenScreen = FirstOpenScreenProvider().build()
window.rootViewController!.present(firstOpenScreen, animated: true)
} else if let lastLaunchedVersion = AppLaunchHistory.lastLaunchedBuildInfo?.version {
if let changeList = ChangeListProvider().changeListController(after: lastLaunchedVersion) {
window.rootViewController!.present(changeList, animated: true)
if presentFirstLaunchOrChangeLog {
if isFirstLaunch {
let firstOpenScreen = FirstOpenScreenProvider().build()
window.rootViewController!.present(firstOpenScreen, animated: true)
} else if let lastLaunchedVersion = AppLaunchHistory.lastLaunchedBuildInfo?.version {
if let changeList = ChangeListProvider().changeListController(after: lastLaunchedVersion) {
window.rootViewController!.present(changeList, animated: true)
}
}
}

Expand Down
6 changes: 4 additions & 2 deletions ReadingList/ViewControllers/Add/ScanBarcode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,11 @@ final class ScanBarcode: UIViewController {
private func setupAvSession() {
#if DEBUG
if CommandLine.arguments.contains("--UITests_Screenshots") {
let imageView = UIImageView(frame: view.frame)
// Not sure why, but the view frame seems way to big when running on iPad
let frameToUse = UIDevice.current.userInterfaceIdiom == .pad ? CGRect(x: 0, y: 0, width: 600, height: 600) : view.frame
let imageView = UIImageView(frame: frameToUse)
imageView.image = UIImage(named: "example_barcode.jpg")!
imageView.contentMode = .scaleAspectFill
imageView.image = #imageLiteral(resourceName: "example_barcode.jpg")
view.addSubview(imageView)
return
}
Expand Down
12 changes: 3 additions & 9 deletions ReadingList_UITests/Screenshots.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class Screenshots: XCTestCase {

func testSnapshot() {

// Screenshot is designed for iOS 13 only
guard #available(iOS 13.0, *) else { return }
// Screenshot is designed for iOS 14 only
guard #available(iOS 14.0, *) else { return }

let app = ReadingListApp()
app.clickTab(.toRead)
Expand All @@ -50,7 +50,7 @@ class Screenshots: XCTestCase {
app.swipeDown()
}
app.navigationBars["Finished"].buttons["Add"].tap()
app.sheets["Add New Book"].buttons["Scan Barcode"].tap()
app.collectionViews.buttons["Scan Barcode"].tap()
snapshot("2_ScanBarcode")

app.navigationBars["Scan Barcode"].buttons["Cancel"].tap()
Expand Down Expand Up @@ -93,11 +93,5 @@ class Screenshots: XCTestCase {
app.swipeUp()
}
snapshot("5_Organise")

//app.tabBars.buttons["Settings"].tap()
//app.tables.staticTexts["General"].tap()
//app.tables.staticTexts["Black"].tap()
//app.tabBars.buttons["To Read"].tap()
//snapshot("6_DarkMode")
}
}
70 changes: 32 additions & 38 deletions ReadingList_UITests/SnapshotHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,13 @@ func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) {
}

enum SnapshotError: Error, CustomDebugStringConvertible {
case cannotDetectUser
case cannotFindHomeDirectory
case cannotFindSimulatorHomeDirectory
case cannotAccessSimulatorHomeDirectory(String)
case cannotRunOnPhysicalDevice

var debugDescription: String {
switch self {
case .cannotDetectUser:
return "Couldn't find Snapshot configuration files - can't detect current user "
case .cannotFindHomeDirectory:
return "Couldn't find Snapshot configuration files - can't detect `Users` dir"
case .cannotFindSimulatorHomeDirectory:
return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable."
case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome):
return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?"
case .cannotRunOnPhysicalDevice:
return "Can't use Snapshot on a physical device."
}
Expand All @@ -75,7 +66,7 @@ open class Snapshot: NSObject {
Snapshot.waitForAnimations = waitForAnimations

do {
let cacheDir = try pathPrefix()
let cacheDir = try getCacheDirectory()
Snapshot.cacheDirectory = cacheDir
setLanguage(app)
setLocale(app)
Expand Down Expand Up @@ -174,6 +165,8 @@ open class Snapshot: NSObject {
}

let screenshot = XCUIScreen.main.screenshot()
let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image

guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return }

do {
Expand All @@ -183,14 +176,27 @@ open class Snapshot: NSObject {
simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "")

let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")
try screenshot.pngRepresentation.write(to: path)
try image.pngData()?.write(to: path, options: .atomic)
} catch let error {
NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png")
NSLog(error.localizedDescription)
}
#endif
}

class func fixLandscapeOrientation(image: UIImage) -> UIImage {
if #available(iOS 10.0, *) {
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
let renderer = UIGraphicsImageRenderer(size: image.size, format: format)
return renderer.image { context in
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
}
} else {
return image
}
}

class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) {
#if os(tvOS)
return
Expand All @@ -206,51 +212,39 @@ open class Snapshot: NSObject {
_ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout)
}

class func pathPrefix() throws -> URL? {
let homeDir: URL
class func getCacheDirectory() throws -> URL {
let cachePath = "Library/Caches/tools.fastlane"
// on OSX config is stored in /Users/<username>/Library
// and on iOS/tvOS/WatchOS it's in simulator's home dir
#if os(OSX)
guard let user = ProcessInfo().environment["USER"] else {
throw SnapshotError.cannotDetectUser
}

guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else {
throw SnapshotError.cannotFindHomeDirectory
let homeDir = URL(fileURLWithPath: NSHomeDirectory())
return homeDir.appendingPathComponent(cachePath)
#elseif arch(i386) || arch(x86_64)
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
throw SnapshotError.cannotFindSimulatorHomeDirectory
}

homeDir = usersDir.appendingPathComponent(user)
let homeDir = URL(fileURLWithPath: simulatorHostHome)
return homeDir.appendingPathComponent(cachePath)
#else
#if arch(i386) || arch(x86_64)
guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
throw SnapshotError.cannotFindSimulatorHomeDirectory
}
guard let homeDirUrl = URL(string: simulatorHostHome) else {
throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome)
}
homeDir = URL(fileURLWithPath: homeDirUrl.path)
#else
throw SnapshotError.cannotRunOnPhysicalDevice
#endif
throw SnapshotError.cannotRunOnPhysicalDevice
#endif
return homeDir.appendingPathComponent("Library/Caches/tools.fastlane")
}
}

private extension XCUIElementAttributes {
var isNetworkLoadingIndicator: Bool {
if hasWhiteListedIdentifier { return false }
if hasAllowListedIdentifier { return false }

let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20)
let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3)

return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize
}

var hasWhiteListedIdentifier: Bool {
let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]
var hasAllowListedIdentifier: Bool {
let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"]

return whiteListedIdentifiers.contains(identifier)
return allowListedIdentifiers.contains(identifier)
}

func isStatusBar(_ deviceWidth: CGFloat) -> Bool {
Expand Down Expand Up @@ -300,4 +294,4 @@ private extension CGFloat {

// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [1.21]
// SnapshotHelperVersion [1.24]
2 changes: 1 addition & 1 deletion fastlane/Fastfile
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ platform :ios do

desc "Create framed screenshots for a range of devices"
lane :snaps do
snapshot(xcargs: '-only-testing:ReadingList_UITests/Screenshots')
snapshot(xcargs: '-only-testing:ReadingList_UITests/Screenshots', override_status_bar: true)
frame_screenshots(white: true)
end

Expand Down
21 changes: 10 additions & 11 deletions fastlane/Snapfile
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
devices([
# "iPhone SE",
# "iPhone 8",
# "iPhone 8 Plus",
# "iPhone 11 Pro",
# "iPhone 11 Pro Max",
# "iPad Pro (9.7-inch)",
# "iPad Pro (12.9-inch)",
"iPad Pro (12.9-inch) (3rd generation)"
#"iPhone SE (1st generation)",
#"iPhone 8",
#"iPhone 8 Plus",
#"iPhone 11 Pro",
"iPhone 11 Pro Max",
"iPad Pro (9.7-inch)",
"iPad Pro (12.9-inch) (4th generation)"
])
languages([
"en-GB",
# "en-US"
"en-GB"
])
scheme("ReadingList_UITests")
workspace("ReadingList.xcworkspace")
ios_version("14.0")
#clear_previous_screenshots(true)
reinstall_app(true)
concurrent_simulators(false)

# Arguments to pass to the app on launch. See https://docs.fastlane.tools/actions/snapshot/#launch-arguments
# launch_arguments(["--reset", "--UITests", "--UITests_PopulateData", "--UITests_Screenshots", "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryXL"])
#launch_arguments(["--reset", "--UITests", "--UITests_PopulateData", "--UITests_Screenshots", "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryXL"])

# For more information about all available options run
# fastlane action snapshot
35 changes: 2 additions & 33 deletions project.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ options:
indentWith: 4
bundleIdPrefix: com.andrewbennet
groupOrdering:
- order: [ReadingList, ReadingList_Foundation, ReadingList_UITests, ReadingList_UnitTests, ReadingListWidget, Debug]
- order: [ReadingList, ReadingList_Foundation, ReadingList_UITests, ReadingList_UnitTests, ReadingListWidget, Debug, fastlane]

packages:
Cosmos:
Expand Down Expand Up @@ -36,6 +36,7 @@ packages:

fileGroups:
- Debug/
- fastlane/
- README.md
- Podfile
- project.yml
Expand Down Expand Up @@ -137,38 +138,6 @@ targets:
scheme:
testTargets:
- ReadingList_UITests
preActions:
- name: Set simulator status bar overrides
settingsTarget: ReadingList_UITests
script: |
function version {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}
if [[ "${SDKROOT}" != *"simulator"* ]]; then
exit 0;
fi
if [ $(version "${TARGET_DEVICE_OS_VERSION}") -ge $(version "13") ]; then
xcrun simctl boot "${TARGET_DEVICE_IDENTIFIER}";
xcrun simctl status_bar "${TARGET_DEVICE_IDENTIFIER}" override --dataNetwork wifi --wifiMode active --wifiBars 3 --cellularMode notSupported --batteryState discharging --batteryLevel 100;
fi
postActions:
- name: Reset simulator status bar
settingsTarget: ReadingList_UITests
script: |
function version {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}
if [[ "${SDKROOT}" != *"simulator"* ]]; then
exit 0;
fi
if [ $(version "${TARGET_DEVICE_OS_VERSION}") -ge $(version "13") ]; then
xcrun simctl boot "${TARGET_DEVICE_IDENTIFIER}";
xcrun simctl status_bar "${TARGET_DEVICE_IDENTIFIER}" clear;
fi

ReadingListWidget:
type: app-extension
Expand Down

0 comments on commit 0e871c2

Please sign in to comment.