Last active
September 16, 2023 04:08
-
-
Save mkj-is/344e1399e844085f10a7c06d55dd45a7 to your computer and use it in GitHub Desktop.
Swift to xcpretty screenshot saving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
extension XCTestCase { | |
func assertFailScreenshot(_ closure: @autoclosure () -> Bool, message: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) { | |
if !closure() { | |
takeScreenshot(description: message, file: file, line: line, function: function) | |
if let message = message { | |
XCTFail(message) | |
} else { | |
XCTFail() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
extension XCTestCase { | |
func takeScreenshot(description: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) { | |
guard let fileUrl = URL(string: file) else { | |
return | |
} | |
let projectPath = fileUrl.deletingLastPathComponent().deletingLastPathComponent() | |
let filename = screenshotFilename(description: description, fileUrl: fileUrl, line: line, function: function) | |
let screenshot = XCUIScreen.main.screenshot() | |
let saveUrl = projectPath | |
.appendingPathComponent("build") | |
.appendingPathComponent("reports") | |
.appendingPathComponent(filename) | |
let fileURLWithPath = URL(fileURLWithPath: saveUrl.path) | |
try! FileManager.default.createDirectory(at: fileURLWithPath.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) | |
try! screenshot.pngRepresentation.write(to: fileURLWithPath) | |
} | |
private func screenshotFilename(description: String?, fileUrl: URL, line: UInt, function: String) -> String { | |
let testCase = fileUrl.deletingPathExtension().lastPathComponent | |
let trimmedFunction = function.trimmingCharacters(in: .punctuationCharacters) | |
let bundleName = Bundle.main.infoDictionary?["CFBundleName"] as? String | |
let prefix = bundleName?.split(separator: "-").first ?? "" | |
var result = "\(prefix).\(testCase)_\(trimmedFunction)_\(line)" | |
if let description = description { | |
result += " \(description)" | |
} | |
result += ".png" | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment