Skip to content

Instantly share code, notes, and snippets.

@danielmartin
Last active September 16, 2019 07:38
Show Gist options
  • Save danielmartin/2575692acd3cdf59ff2dd5bdd6ed9afe to your computer and use it in GitHub Desktop.
Save danielmartin/2575692acd3cdf59ff2dd5bdd6ed9afe to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
/// Some helpers for having nice test assertions.
public func expectationFailure(
_ reason: String,
trace message: String) {
print(reason, terminator: reason == "" ? "" : "\n")
print(message, terminator: message == "" ? "" : "\n")
}
public func expectNil<T>(_ value: T?,
_ message: @autoclosure () -> String = "",
file: String = #file, line: UInt = #line) {
if value != nil {
expectationFailure(
"expected optional to be nil\nactual: \"\(value!)\"", trace: message())
}
}
@discardableResult
public func expectNotNil<T>(_ value: T?,
_ message: @autoclosure () -> String = "",
file: String = #file, line: UInt = #line) -> T? {
if value == nil {
expectationFailure("expected optional to be non-nil", trace: message())
}
return value
}
public func expectTrue(_ actual: Bool,
_ message: @autoclosure () -> String = "",
file: String = #file, line: UInt = #line) {
if !actual {
expectationFailure("expected: true", trace: message())
}
}
public func expectEqualTest<T>(
_ expected: T, _ actual: T,
_ message: @autoclosure () -> String = "",
file: String = #file, line: UInt = #line, sameValue equal: (T, T) -> Bool
) {
if !equal(expected, actual) {
expectationFailure(
"expected: \(String(reflecting: expected)) (of type \(String(reflecting: type(of: expected))))\n"
+ "actual: \(String(reflecting: actual)) (of type \(String(reflecting: type(of: actual))))",
trace: message()
)
}
}
public func expectEqual<T : Equatable>(_ expected: T, _ actual: T,
_ message: @autoclosure () -> String = "",
file: String = #file, line: UInt = #line) {
expectEqualTest(expected, actual, message()) {$0 == $1}
}
/// This is the class we will apply reflection to.
class CustomCell : UITableViewCell {
}
/// Perform reflection from bottom to top and assert that NSObject is the maximal in this class hierarchy lattice.
let customCell = Mirror(reflecting: CustomCell())
expectTrue(customCell.subjectType == CustomCell.self)
if let tableViewCell = expectNotNil(customCell.superclassMirror) {
expectTrue(tableViewCell.subjectType == UITableViewCell.self)
if let view = expectNotNil(tableViewCell.superclassMirror) {
expectTrue(view.subjectType == UIView.self)
if let responder = expectNotNil(view.superclassMirror) {
expectTrue(responder.subjectType == UIResponder.self)
if let object = expectNotNil(responder.superclassMirror) {
expectTrue(object.subjectType == NSObject.self)
expectNil(object.superclassMirror)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment