-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExpectFuncDSL.swift
320 lines (267 loc) · 9.56 KB
/
ExpectFuncDSL.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//
// ExpectFuncDSL.swift
// Scout
//
// Created by Brian Gerstle on 6/13/19.
// Copyright © 2019 Brian Gerstle. All rights reserved.
//
import Foundation
public struct FuncDSL {
let context: MockFuncContext
let argChecker: ArgChecker
init(context: MockFuncContext, matchers: KeyValuePairs<String, ArgMatcher>) {
self.init(context: context, matchers: matchers.keyValuePairArray)
}
init(context: MockFuncContext, matchers: [KeyValuePair<String, ArgMatcher>]) {
self.context = context
self.argChecker = ArgChecker(context: context, argMatchers: matchers)
}
/// Expect an Expectation (similar to `ExpectVarDSL#to`).
///
/// mockExample.expect.foo().to(`return`(0))
///
@discardableResult
public func to(
_ expectation: Expectation,
_ file: StaticString = #file,
_ line: UInt = #line
) -> FuncDSL {
return to(ExpectationFuncWrapper(expectation: expectation), file, line)
}
/// Set an expectation with a higher-order function.
///
/// func incrementBy(_ amount: Int) -> FuncExpectationBlock {
/// return { args in
/// return args.first as! Int + amount
/// }
/// }
/// mockExample.expect.foo.to(incrementBy(1))
///
/// - Parameters:
/// - block: A function that accepts the arguments to the expected function call.
/// - times: The number of times this expectation should occur.
/// - Returns: The DSL for further chaining.
@discardableResult
public func to(
_ block: @escaping FuncExpectationBlock,
times: Int = 1,
_ file: StaticString = #file,
_ line: UInt = #line
) -> FuncDSL {
return to(CallFuncExpectation(block: block, times: times), file, line)
}
// Always call the specified higher order function (see `to(_ block:...)`).
public func toAlways(
_ block: @escaping FuncExpectationBlock,
_ file: StaticString = #file,
_ line: UInt = #line) {
to(AlwaysCallFuncExpectation(block: block), file, line)
}
/// Expect the function to be called, without specifying a behavior (e.g. a function
/// that doesn't return anything but must be called for some side effect).
///
/// mockExample.expect.foo().toBeCalled()
///
/// - Parameters:
/// - times: How many times it should be called.
/// - Returns: An expectation that verifies the function is called the specified number of times.
@discardableResult
public func toBeCalled(
times: UInt = 1,
_ file: StaticString = #file,
_ line: UInt = #line
) -> FuncDSL {
let noop: FuncExpectationBlock = { _ in () }
(0..<times).forEach { _ in to(CallFuncExpectation(block: noop), file, line) }
return self
}
/// Chain expectations on a function:
///
/// expect.foo.to(`return`(1)).and.to(`return`(5))
///
public var and: FuncDSL {
return self
}
@discardableResult
private func to(
_ expectation: FuncExpectation,
_ file: StaticString = #file,
_ line: UInt = #line
) -> FuncDSL {
let wrappedExpectation = ArgCheckingFuncExpectationWrapper(
expectation: expectation,
argChecker: argChecker,
location: (file: file, line: line)
)
context.mock.append(expectation: wrappedExpectation, for: context.funcName)
return self
}
}
/// Expect a function to throw an error.
///
/// mockThrowsExample.expect.throwingFunc.to(`throw`(SomeError()))
///
/// - Parameter error: The error to throw, constructed lazily.
/// - Returns: A function that throws the specified error.
public func `throw`(_ error: @escaping @autoclosure () -> Error) -> FuncExpectationBlock {
return { _ in
throw error()
}
}
// Alias in case backticks aren't desired.
let throwError = `throw`
protocol MockFuncContext {
var mock: Mock { get }
var funcName: String { get }
}
@dynamicCallable
public class ExpectFuncDSL : MockFuncContext {
let mock: Mock
let funcName: String
// Declared as var because `argMatchers` are set when the dynamicCallable is called (after
// ExpectFuncDSL is returned as a dynamicMember of ExpectDSL).
var argMatchers: [ArgMatcher]! = nil
init(mock: Mock, funcName: String) {
self.mock = mock
self.funcName = funcName
}
public func dynamicallyCall(withKeywordArguments argMatchers: KeyValuePairs<String, ArgMatcher>) -> FuncDSL {
return FuncDSL(context: self, matchers: argMatchers)
}
}
public typealias FuncExpectationBlock = (KeyValuePairs<String, Any?>) throws -> Any?
public protocol FuncExpectation {
func hasNext() -> Bool
func nextBlock() -> FuncExpectationBlock
func shouldVerify() -> Bool
}
extension FuncExpectation {
func shouldVerify() -> Bool {
return true
}
}
// Using plain array of tuples instead of KeyValuePairs because the latter
// can't be instantiated directly or manipulated.
typealias KeyValuePair<K, V> = (key: K, value: V)
extension KeyValuePairs {
var keyValuePairArray: [KeyValuePair<Key, Value>] {
return map { $0 }
}
}
struct ArgChecker {
let context: MockFuncContext
let argMatchers: [KeyValuePair<String, ArgMatcher>]
func wrap(_ block: @escaping FuncExpectationBlock, location: SourceLocation) -> FuncExpectationBlock {
return { args in
self.checkArgs(args: args, location: location)
return try block(args)
}
}
internal func checkArgs(args: KeyValuePairs<String, Any?>, location: SourceLocation) {
guard args.count == self.argMatchers.count else {
recordFailure("Expected \(self.argMatchers.count) arguments, but got \(args.count)",
file: location.file,
line: location.line)
return
}
let expectedKeys = self.argMatchers.map { $0.key },
actualKeys = args.map { $0.key }
guard expectedKeys == actualKeys else {
recordFailure("Expected call with keywords \(expectedKeys), got \(actualKeys).",
file: location.file,
line: location.line)
return
}
let enumeratedArgsAndMatchers = zip(args, self.argMatchers).enumerated().map { (arg) -> (index: Int, arg: KeyValuePair<String, Any?>, matcher: (key: String, value: ArgMatcher)) in
let (offset, (arg, matcher)) = arg
return (index: offset, arg: arg, matcher: matcher)
}
let allMatch = enumeratedArgsAndMatchers.allSatisfy { (index, arg, matcher) in
return matcher.value.matches(arg: arg.value)
}
guard allMatch else {
let header = ["Arguments to \(context.funcName) didn't match:"],
body = enumeratedArgsAndMatchers.map { (arg) -> String in
let (index, arg, matcher) = arg,
label = matcher.key.count > 1 ? matcher.key : "[\(index)]",
bullet = matcher.value.matches(arg: arg.value) ? "✅" : "❌"
return " \(bullet) \(label): "
+ "Expected \(matcher.value.description), "
+ "got \(arg.value.map { String(describing: $0) } ?? "nil")"
}
recordFailure((header + body).joined(separator: "\n"),
file: location.file,
line: location.line)
return
}
}
}
class CallFuncExpectation : FuncExpectation {
var remainingCalls: Int
let block: FuncExpectationBlock
init(block: @escaping FuncExpectationBlock, times: Int = 1) {
self.block = block
assert(times > 0)
self.remainingCalls = times
}
func hasNext() -> Bool {
return remainingCalls > 0
}
func nextBlock() -> FuncExpectationBlock {
remainingCalls -= 1
return block
}
}
class AlwaysCallFuncExpectation : FuncExpectation {
let block: FuncExpectationBlock
init(block: @escaping FuncExpectationBlock) {
self.block = block
}
func hasNext() -> Bool {
return true
}
func nextBlock() -> FuncExpectationBlock {
return block
}
func shouldVerify() -> Bool {
return false
}
}
class ExpectationFuncWrapper : FuncExpectation {
let expectation: Expectation
init(expectation: Expectation) {
self.expectation = expectation
}
func nextBlock() -> FuncExpectationBlock {
// must eagerly retrieve next value, otherwise (if it's a consumable expectation)
// it won't be marked as consumed & removed in the Mock logic (which checks before
// the returned block is invoked)
let result = self.expectation.nextValue()
return { _ in result }
}
func hasNext() -> Bool {
return expectation.hasNext()
}
func shouldVerify() -> Bool {
return expectation.shouldVerify()
}
}
class ArgCheckingFuncExpectationWrapper : Expectation {
let expectation: FuncExpectation
let argChecker: ArgChecker
let location: SourceLocation
init(expectation: FuncExpectation, argChecker: ArgChecker, location: SourceLocation) {
self.expectation = expectation
self.argChecker = argChecker
self.location = location
}
public func hasNext() -> Bool {
return expectation.hasNext()
}
public func nextValue() -> Any? {
return argChecker.wrap(expectation.nextBlock(), location: location)
}
public func shouldVerify() -> Bool {
return expectation.shouldVerify()
}
}