-
Notifications
You must be signed in to change notification settings - Fork 61
/
CwlDebugContextTests.swift
613 lines (524 loc) · 17.8 KB
/
CwlDebugContextTests.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//
// CwlDebugContextTests.swift
// CwlUtils
//
// Created by Matt Gallagher on 2016/09/13.
// Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
import XCTest
import CwlUtils
class DebugContextTests: XCTestCase {
func testDirectInvoke() {
let coordinator = DebugContextCoordinator()
var checkpoint = false
coordinator.direct.invoke {
checkpoint = true
XCTAssert(coordinator.currentThread == .unspecified)
XCTAssert(coordinator.currentTime == 0)
}
XCTAssert(checkpoint)
}
func testDirectInvokeAsync() {
let coordinator = DebugContextCoordinator()
var checkpoint = false
coordinator.direct.invokeAsync {
checkpoint = true
XCTAssert(coordinator.currentThread == .global)
XCTAssert(coordinator.currentTime == 1)
}
XCTAssert(!checkpoint)
coordinator.runScheduledTasks()
XCTAssert(checkpoint)
}
func testDirectInvokeAndWait() {
let coordinator = DebugContextCoordinator()
var checkpoint = false
coordinator.direct.invokeSync {
checkpoint = true
XCTAssert(coordinator.currentThread == .unspecified)
XCTAssert(coordinator.currentTime == 0)
}
XCTAssert(checkpoint)
}
func testDirectSingleTimer() {
let coordinator = DebugContextCoordinator()
var checkpoint1 = false
var checkpoint2 = false
var timer2: Lifetime? = nil
let timer1 = coordinator.direct.singleTimer(interval: .seconds(10), leeway: .seconds(0)) {
checkpoint1 = true
XCTAssert(coordinator.currentThread == .global)
XCTAssert(coordinator.currentTime == 10_000_000_000)
timer2 = coordinator.direct.singleTimer(interval: .seconds(10), leeway: .seconds(0)) {
checkpoint2 = true
XCTAssert(coordinator.currentThread == .global)
XCTAssert(coordinator.currentTime == 20_000_000_000)
}
XCTAssert(!checkpoint2)
}
XCTAssert(!checkpoint1)
coordinator.runScheduledTasks()
XCTAssert(checkpoint1)
XCTAssert(checkpoint2)
withExtendedLifetime(timer1) {}
withExtendedLifetime(timer2) {}
var timer3 = coordinator.direct.singleTimer(interval: .seconds(10), leeway: .seconds(0)) {
XCTFail()
}
timer3.cancel()
coordinator.runScheduledTasks()
}
func testDirectSingleTimerWithParameter() {
let coordinator = DebugContextCoordinator()
var checkpoint1 = false
let timer1 = coordinator.direct.singleTimer(parameter: 23, interval: .seconds(10), leeway: .seconds(0)) { p in
checkpoint1 = true
XCTAssert(p == 23)
XCTAssert(coordinator.currentThread == .global)
XCTAssert(coordinator.currentTime == 10_000_000_000)
}
XCTAssert(!checkpoint1)
coordinator.runScheduledTasks()
XCTAssert(checkpoint1)
withExtendedLifetime(timer1) {}
}
func testDirectPeriodicTimer() {
let coordinator = DebugContextCoordinator()
var results = [(Int, UInt64)]()
var timer1: Lifetime? = nil
timer1 = coordinator.direct.periodicTimer(interval: .seconds(3), leeway: .seconds(0)) {
results.append((0, coordinator.currentTime))
if results.count >= 9 {
timer1?.cancel()
}
}
var timer2: Lifetime? = nil
timer2 = coordinator.direct.periodicTimer(interval: .seconds(10), leeway: .seconds(0)) {
results.append((1, coordinator.currentTime))
if results.count >= 9 {
timer2?.cancel()
}
}
coordinator.runScheduledTasks()
XCTAssert(results.count == 10)
XCTAssert(results.at(0).map { $0.0 == 0 && $0.1 == 3_000_000_000 } == true)
XCTAssert(results.at(1).map { $0.0 == 0 && $0.1 == 6_000_000_000 } == true)
XCTAssert(results.at(2).map { $0.0 == 0 && $0.1 == 9_000_000_000 } == true)
XCTAssert(results.at(3).map { $0.0 == 1 && $0.1 == 10_000_000_000 } == true)
XCTAssert(results.at(4).map { $0.0 == 0 && $0.1 == 12_000_000_000 } == true)
XCTAssert(results.at(5).map { $0.0 == 0 && $0.1 == 15_000_000_000 } == true)
XCTAssert(results.at(6).map { $0.0 == 0 && $0.1 == 18_000_000_000 } == true)
XCTAssert(results.at(7).map { $0.0 == 1 && $0.1 == 20_000_000_000 } == true)
XCTAssert(results.at(8).map { $0.0 == 0 && $0.1 == 21_000_000_000 } == true)
XCTAssert(results.at(9).map { $0.0 == 1 && $0.1 == 30_000_000_000 } == true)
}
func testDirectPeriodicTimerWithParameter() {
let coordinator = DebugContextCoordinator()
var results = [(Int, UInt64)]()
var timer1: Lifetime? = nil
timer1 = coordinator.direct.periodicTimer(parameter: 23, interval: .seconds(3), leeway: .seconds(0)) { p in
XCTAssert(p == 23)
results.append((0, coordinator.currentTime))
if results.count >= 9 {
timer1?.cancel()
}
}
var timer2: Lifetime? = nil
timer2 = coordinator.direct.periodicTimer(parameter: 45, interval: .seconds(10), leeway: .seconds(0)) { p in
XCTAssert(p == 45)
results.append((1, coordinator.currentTime))
if results.count >= 9 {
timer2?.cancel()
}
}
coordinator.runScheduledTasks()
XCTAssert(results.count == 10)
XCTAssert(results.at(0).map { $0.0 == 0 && $0.1 == 3_000_000_000 } == true)
XCTAssert(results.at(1).map { $0.0 == 0 && $0.1 == 6_000_000_000 } == true)
XCTAssert(results.at(2).map { $0.0 == 0 && $0.1 == 9_000_000_000 } == true)
XCTAssert(results.at(3).map { $0.0 == 1 && $0.1 == 10_000_000_000 } == true)
XCTAssert(results.at(4).map { $0.0 == 0 && $0.1 == 12_000_000_000 } == true)
XCTAssert(results.at(5).map { $0.0 == 0 && $0.1 == 15_000_000_000 } == true)
XCTAssert(results.at(6).map { $0.0 == 0 && $0.1 == 18_000_000_000 } == true)
XCTAssert(results.at(7).map { $0.0 == 1 && $0.1 == 20_000_000_000 } == true)
XCTAssert(results.at(8).map { $0.0 == 0 && $0.1 == 21_000_000_000 } == true)
XCTAssert(results.at(9).map { $0.0 == 1 && $0.1 == 30_000_000_000 } == true)
}
func testMainInvoke() {
let coordinator1 = DebugContextCoordinator(initialThread: .main)
var checkpoint1 = false
coordinator1.main.invoke {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 0)
}
XCTAssert(checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
let coordinator2 = DebugContextCoordinator()
var checkpoint2 = false
coordinator2.main.invoke {
checkpoint2 = true
XCTAssert(coordinator2.currentThread == .main)
XCTAssert(coordinator2.currentTime == 1)
}
XCTAssert(!checkpoint2)
coordinator2.runScheduledTasks()
XCTAssert(checkpoint2)
}
func testMainAsyncInvoke() {
let coordinator1 = DebugContextCoordinator(initialThread: .main)
var checkpoint1 = false
coordinator1.mainAsync.invoke {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
}
func testDefaultInvoke() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.global.invoke {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .global)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
}
func testSyncQueueInvoke() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.syncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invoke {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 0)
}
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testAsyncQueueInvoke() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.asyncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invoke {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testMainInvokeAsync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.main.invokeAsync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
let coordinator2 = DebugContextCoordinator()
var checkpoint2 = false
coordinator2.main.invokeAsync {
checkpoint2 = true
XCTAssert(coordinator2.currentThread == .main)
XCTAssert(coordinator2.currentTime == 1)
}
XCTAssert(!checkpoint2)
coordinator2.runScheduledTasks()
XCTAssert(checkpoint2)
}
func testMainAsyncInvokeAsync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.mainAsync.invokeAsync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
}
func testDefaultInvokeAsync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.global.invokeAsync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .global)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
}
func testSyncQueueInvokeAsync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.syncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invokeAsync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testAsyncQueueInvokeAsync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.asyncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invokeAsync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(!checkpoint1)
coordinator1.runScheduledTasks()
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testMainInvokeAndWait() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.main.invokeSync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(checkpoint1)
let coordinator2 = DebugContextCoordinator()
var checkpoint2 = false
coordinator2.main.invokeSync {
checkpoint2 = true
XCTAssert(coordinator2.currentThread == .main)
XCTAssert(coordinator2.currentTime == 1)
}
XCTAssert(checkpoint2)
}
func testMainAsyncInvokeAndWait() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.mainAsync.invokeSync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .main)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(checkpoint1)
}
func testDefaultInvokeAndWait() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
coordinator1.global.invokeSync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread == .global)
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(checkpoint1)
}
func testSyncQueueInvokeSync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.syncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invokeSync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 0)
}
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testAsyncQueueInvokeSync() {
let coordinator1 = DebugContextCoordinator()
var checkpoint1 = false
let ec = coordinator1.asyncQueue()
if case .custom(_ as DebugContext) = ec {
ec.invokeSync {
checkpoint1 = true
XCTAssert(coordinator1.currentThread.matches(ec))
XCTAssert(coordinator1.currentTime == 1)
}
XCTAssert(checkpoint1)
} else {
XCTFail()
}
}
func testRelativeAsync() {
let coordinator1 = DebugContextCoordinator()
let async = coordinator1.asyncQueue()
let relativeAsync = async.relativeAsync()
if case .custom(let relative as DebugContext) = relativeAsync, case .custom(let global as DebugContext) = coordinator1.global {
return XCTAssert(relative.thread == global.thread)
} else {
return XCTFail()
}
}
#if false
func testTimeoutServiceSuccessHostTime() {
let ex = expectation(description: "Waiting for timeout callback")
// Use our debug `StringService`
let service = TimeoutService(work: dummyAsyncWork(duration: 2.0))
// Set up the time data we need
let startTime = mach_absolute_time()
let timeoutTime = 1.0
let targetTime = UInt64(timeoutTime * Double(NSEC_PER_SEC))
let leeway = UInt64(0.01 * Double(NSEC_PER_SEC))
service.start(timeout: timeoutTime) { r in
// Measure and test the time elapsed
let endTime = mach_absolute_time()
XCTAssert(endTime - startTime > targetTime - leeway)
XCTAssert(endTime - startTime < targetTime + leeway)
XCTAssert(r.value == nil)
ex.fulfill()
}
// Wait for all scheduled actions to occur
waitForExpectations(timeout: 10, handler: nil)
}
#endif
func testTimeoutServiceSuccess() {
let coordinator = DebugContextCoordinator()
var result: Result<String, Error>? = nil
let service = TimeoutService(context: coordinator.global, work: dummyAsyncWork(duration: 2.0))
service.start(timeout: 10) { r in
result = r
}
coordinator.runScheduledTasks()
coordinator.reset()
withExtendedLifetime(service) {}
XCTAssert(result?.value == dummySuccessResponse)
}
func testTimeoutServiceCancelled() {
let coordinator = DebugContextCoordinator()
// Test the service released case
do {
let service = TimeoutService(context: coordinator.global, work: dummyAsyncWork(duration: 2.0))
service.start(timeout: 10) { r in
XCTFail()
}
}
coordinator.runScheduledTasks()
}
func testTimeoutServiceTimeout() {
let coordinator = DebugContextCoordinator()
let context = coordinator.syncQueue()
// Construct the `TimeoutService` using our debug context
let service = TimeoutService(context: context, work: dummyAsyncWork(duration: 2.0))
// Run the `connect` function
let timeoutTime = 1.0
var result: Result<String, Error>? = nil
service.start(timeout: timeoutTime) { r in
result = r
XCTAssert(coordinator.currentTime == UInt64(timeoutTime * Double(NSEC_PER_SEC)))
XCTAssert(coordinator.currentThread.matches(context))
}
// Perform all scheduled tasks immediately
coordinator.runScheduledTasks()
// Ensure we got the correct result
XCTAssert(result?.error as? TimeoutService.Timeout != nil)
withExtendedLifetime(service) {}
}
}
class TimeoutService {
struct Timeout: Error {}
// This service performs one action at a time, lifetime tied to the service
// The service retains the timeout timer which, in turn, returns the
// underlying service
var currentAction: Lifetime? = nil
// Define the interface for the underlying connection
typealias ResultHandler = (Result<String, Error>) -> Void
typealias WorkFunction = (Exec, @escaping ResultHandler) -> Lifetime
// This is the configurable connection to the underlying service
let work: WorkFunction
// Every action for this service should occur in in this queue
let context: Exec
// Construction of the Service lets us specify the underlying service
init(context: Exec = .global, work: @escaping WorkFunction = NetworkService.init) {
self.work = work
self.context = context.serialized()
}
// This `TimeoutService` invokes the `underlyingConnect` and starts a timer
func start(timeout seconds: Double, handler: @escaping ResultHandler) {
var previousAction: Lifetime? = nil
context.invokeSync {
previousAction = self.currentAction
let current = AggregateLifetime()
// Run the underlying connection
let underlyingAction = self.work(self.context) { [weak current] result in
// Cancel the timer if the success occurs first
current?.cancel()
handler(result)
}
// Run the timeout timer
let timer = self.context.singleTimer(interval: .interval(seconds)) { [weak current] in
// Cancel the connection if the timer fires first
current?.cancel()
handler(.failure(Timeout()))
}
current += timer
current += underlyingAction
self.currentAction = current
}
// Good rule of thumb: never release lifetime objects inside a mutex
withExtendedLifetime(previousAction) {}
}
}
let dummySuccessResponse = "Here's a string"
func dummyAsyncWork(duration: Double) -> TimeoutService.WorkFunction {
return { exec, handler in
exec.singleTimer(interval: .interval(duration)) {
handler(.success(dummySuccessResponse))
}
}
}
// Dummy network service used to fulfill interface requirements. Obviously, doesn't really connect to the network but you could imagine something that fetches an HTTP resource.
class NetworkService: Lifetime {
var timer: Lifetime
init(context: Exec, handler: @escaping TimeoutService.ResultHandler) {
timer = context.singleTimer(interval: .interval(5.0)) {
handler(.success(dummySuccessResponse))
}
}
func cancel() {
timer.cancel()
}
}