Revision control

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
@testable import Shared
6
import XCTest
7
8
// Trivial test for using Deferred.
9
10
class DeferredTests: XCTestCase {
11
func testDeferred() {
12
let d = Deferred<Int>()
13
XCTAssertNil(d.peek(), "Value not yet filled.")
14
15
let expectation = self.expectation(description: "Waiting on value.")
16
d.upon({ x in
17
expectation.fulfill()
18
})
19
20
d.fill(5)
21
waitForExpectations(timeout: 10) { (error) in
22
XCTAssertNil(error, "\(error.debugDescription)")
23
}
24
25
XCTAssertEqual(5, d.peek()!, "Value is filled.")
26
}
27
28
func testMultipleUponBlocks() {
29
let e1 = self.expectation(description: "First.")
30
let e2 = self.expectation(description: "Second.")
31
let d = Deferred<Int>()
32
d.upon { x in
33
XCTAssertEqual(x, 5)
34
e1.fulfill()
35
}
36
d.upon { x in
37
XCTAssertEqual(x, 5)
38
e2.fulfill()
39
}
40
d.fill(5)
41
waitForExpectations(timeout: 10, handler: nil)
42
}
43
44
func testOperators() {
45
let e1 = self.expectation(description: "First.")
46
let e2 = self.expectation(description: "Second.")
47
48
let f1: () -> Deferred<Maybe<Int>> = {
49
return deferMaybe(5)
50
}
51
52
let f2: (_ x: Int) -> Deferred<Maybe<String>> = {
53
if $0 == 5 {
54
e1.fulfill()
55
}
56
return deferMaybe("Hello!")
57
}
58
59
// Type signatures:
60
let combined: () -> Deferred<Maybe<String>> = { f1() >>== f2 }
61
let result: Deferred<Maybe<String>> = combined()
62
63
result.upon {
64
XCTAssertEqual("Hello!", $0.successValue!)
65
e2.fulfill()
66
}
67
68
waitForExpectations(timeout: 10, handler: nil)
69
}
70
71
func testPassAccumulate() {
72
let leak = self.expectation(description: "deinit")
73
74
class TestClass {
75
let end: XCTestExpectation
76
init(e: XCTestExpectation) {
77
end = e
78
accumulate([self.aSimpleFunction]).upon { _ in
79
80
}
81
}
82
83
func aSimpleFunction() -> Success {
84
return succeed()
85
}
86
deinit {
87
end.fulfill()
88
}
89
}
90
91
var myclass: TestClass? = TestClass(e: leak)
92
myclass = nil
93
waitForExpectations(timeout: 3, handler: nil)
94
}
95
96
97
func testFailAccumulate() {
98
let leak = self.expectation(description: "deinit")
99
100
class TestError: MaybeErrorType {
101
var description = "Error"
102
}
103
104
class TestClass {
105
let end: XCTestExpectation
106
init(e: XCTestExpectation) {
107
end = e
108
accumulate([self.aSimpleFunction]).upon { _ in
109
110
}
111
}
112
113
func aSimpleFunction() -> Success {
114
return Deferred(value: Maybe(failure: TestError()))
115
}
116
deinit {
117
end.fulfill()
118
}
119
}
120
121
var myclass: TestClass? = TestClass(e: leak)
122
myclass = nil
123
waitForExpectations(timeout: 3, handler: nil)
124
}
125
126
}