Skip to content

Instantly share code, notes, and snippets.

View polac24's full-sized avatar

Bartosz Polaczyk polac24

  • Apple
  • Cupertino
View GitHub Profile
enum Efect: Equatable {
case details(String,Int)
case simple(String)
case dummy
}
class EffectAction<AssociatedValues, Effect: Equatable>{
private let factory:(AssociatedValues)->(Effect)
XCTAssertEqual(addUserArgs, ["myuser1", "myuser2"]) // ✅
extension ArgRecords: Equatable where T: Equatable{
static func == (lhs: ArgRecords<T>, rhs: ArgRecords<T>) -> Bool {
return lhs.history == rhs.history
}
}
class ArgRecords<T>: ExpressibleByArrayLiteral{
public required init(arrayLiteral elements: T...) {
history = elements
}
...
}
// Currently
XCTAssertEqual(addUserArgs[0], "myuser1")
XCTAssertEqual(addUserArgs[1], "myuser2")
XCTAssertEqual(addUserArgs.count, 2)
// Nice to have
XCTAssertEqual(addUserArgs, ["myuser1", "myuser2"]) // ✅
protocol Database {
func addUser<T>(user: T) -> Bool
}
class DatabaseStub<User>: Database {
lazy var addUserAction: (T) -> Bool
func addUser<T>(user: T) -> Bool {
return addUserAction(user as! User)
}
}
func stub<I,O>(of: (I) throws -> (O)) -> (I) throws -> (O){
return nil!
}
func niceStub<I,O>(of: (I) throws -> (O), thatReturns: O) -> (I) throws -> (O){
return { _ in thatReturns }
}
func niceStub<I,O,E:Error>(of: (I) throws -> (O), thatThrows error: E) -> (I) throws -> (O){
return { _ in throw error }
}
func niceStub<I,O: DefaultProvidable>(of: (I) throws -> (O)) -> (I) throws -> (O){
XCTAssertEqual(addUserArgs[0], "myuser") // ✅
XCTAssertEqual(addUserArgs[100], "myuser") // 🛑, but doesn't crash even count of addUserArgs is 1
class ArgRecords<T>{
private(set) var history: [T] = []
func record(_ t: T){
history.append(t)
}
subscript(_ i: Int) -> T? {
guard i < history.count else {return nil}
return history[i]
}
var count: Int {
// Globally defined helper function that injects a spy
// to record all stub function calls along with their arguments
func spyCalls<I,O>(of stub: inout (I) -> (O)) -> (ArgRecords<I>) {
// data structure to track all args
let argRecords = ArgRecords<I>()
// keep previously used stub function
let orginalStub = stub
// override stub implementation (inout stub argument)
stub = { [weak weakArgRecords = argRecords] i in
weakArgRecords?.record(i) // store arg to the data structure