-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathJavaScriptEventLoopTests.swift
260 lines (230 loc) · 8.48 KB
/
JavaScriptEventLoopTests.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
import JavaScriptEventLoop
import JavaScriptKit
import XCTest
final class JavaScriptEventLoopTests: XCTestCase {
// Helper utilities for testing
struct MessageError: Error {
let message: String
let file: StaticString
let line: UInt
let column: UInt
init(_ message: String, file: StaticString, line: UInt, column: UInt) {
self.message = message
self.file = file
self.line = line
self.column = column
}
}
func expectAsyncThrow<T>(
_ body: @autoclosure () async throws -> T, file: StaticString = #file, line: UInt = #line,
column: UInt = #column
) async throws -> Error {
do {
_ = try await body()
} catch {
return error
}
throw MessageError("Expect to throw an exception", file: file, line: line, column: column)
}
func performanceNow() -> Double {
return JSObject.global.performance.now().number!
}
func measureTime(_ block: () async throws -> Void) async rethrows -> Double {
let start = performanceNow()
try await block()
return performanceNow() - start
}
// Error type used in tests
struct E: Error, Equatable {
let value: Int
}
// MARK: - Task Tests
func testTaskInit() async throws {
// Test Task.init value
let handle = Task { 1 }
let value = await handle.value
XCTAssertEqual(value, 1)
}
func testTaskInitThrows() async throws {
// Test Task.init throws
let throwingHandle = Task {
throw E(value: 2)
}
let error = try await expectAsyncThrow(await throwingHandle.value)
let e = try XCTUnwrap(error as? E)
XCTAssertEqual(e, E(value: 2))
}
func testTaskSleep() async throws {
// Test Task.sleep(_:)
let sleepDiff = try await measureTime {
try await Task.sleep(nanoseconds: 200_000_000)
}
XCTAssertGreaterThanOrEqual(sleepDiff, 200)
// Test shorter sleep duration
let shortSleepDiff = try await measureTime {
try await Task.sleep(nanoseconds: 100_000_000)
}
XCTAssertGreaterThanOrEqual(shortSleepDiff, 100)
}
func testTaskPriority() async throws {
// Test Job reordering based on priority
class Context: @unchecked Sendable {
var completed: [String] = []
}
let context = Context()
// When no priority, they should be ordered by the enqueued order
let t1 = Task(priority: nil) {
context.completed.append("t1")
}
let t2 = Task(priority: nil) {
context.completed.append("t2")
}
_ = await (t1.value, t2.value)
XCTAssertEqual(context.completed, ["t1", "t2"])
context.completed = []
// When high priority is enqueued after a low one, they should be re-ordered
let t3 = Task(priority: .low) {
context.completed.append("t3")
}
let t4 = Task(priority: .high) {
context.completed.append("t4")
}
let t5 = Task(priority: .low) {
context.completed.append("t5")
}
_ = await (t3.value, t4.value, t5.value)
XCTAssertEqual(context.completed, ["t4", "t3", "t5"])
}
// MARK: - Promise Tests
func testPromiseResolution() async throws {
// Test await resolved Promise
let p = JSPromise(resolver: { resolve in
resolve(.success(1))
})
let resolutionValue = try await p.value
XCTAssertEqual(resolutionValue, .number(1))
let resolutionResult = await p.result
XCTAssertEqual(resolutionResult, .success(.number(1)))
}
func testPromiseRejection() async throws {
// Test await rejected Promise
let rejectedPromise = JSPromise(resolver: { resolve in
resolve(.failure(.number(3)))
})
let promiseError = try await expectAsyncThrow(try await rejectedPromise.value)
let jsValue = try XCTUnwrap(promiseError as? JSException).thrownValue
XCTAssertEqual(jsValue, .number(3))
let rejectionResult = await rejectedPromise.result
XCTAssertEqual(rejectionResult, .failure(.number(3)))
}
func testPromiseThen() async throws {
// Test Async JSPromise: then
let promise = JSPromise { resolve in
_ = JSObject.global.setTimeout!(
JSClosure { _ in
resolve(.success(JSValue.number(3)))
return .undefined
}.jsValue,
100
)
}
let promise2 = promise.then { result in
try await Task.sleep(nanoseconds: 100_000_000)
return String(result.number!)
}
let thenDiff = try await measureTime {
let result = try await promise2.value
XCTAssertEqual(result, .string("3.0"))
}
XCTAssertGreaterThanOrEqual(thenDiff, 200)
}
func testPromiseThenWithFailure() async throws {
// Test Async JSPromise: then(success:failure:)
let failingPromise = JSPromise { resolve in
_ = JSObject.global.setTimeout!(
JSClosure { _ in
resolve(.failure(JSError(message: "test").jsValue))
return .undefined
}.jsValue,
100
)
}
let failingPromise2 = failingPromise.then { _ in
throw MessageError("Should not be called", file: #file, line: #line, column: #column)
} failure: { err in
return err
}
let failingResult = try await failingPromise2.value
XCTAssertEqual(failingResult.object?.message, .string("test"))
}
func testPromiseCatch() async throws {
// Test Async JSPromise: catch
let catchPromise = JSPromise { resolve in
_ = JSObject.global.setTimeout!(
JSClosure { _ in
resolve(.failure(JSError(message: "test").jsValue))
return .undefined
}.jsValue,
100
)
}
let catchPromise2 = catchPromise.catch { err in
try await Task.sleep(nanoseconds: 100_000_000)
return err
}
let catchDiff = try await measureTime {
let result = try await catchPromise2.value
XCTAssertEqual(result.object?.message, .string("test"))
}
XCTAssertGreaterThanOrEqual(catchDiff, 200)
}
// MARK: - Continuation Tests
func testContinuation() async throws {
// Test Continuation
let continuationValue = await withUnsafeContinuation { cont in
cont.resume(returning: 1)
}
XCTAssertEqual(continuationValue, 1)
let continuationError = try await expectAsyncThrow(
try await withUnsafeThrowingContinuation { (cont: UnsafeContinuation<Never, Error>) in
cont.resume(throwing: E(value: 2))
}
)
let errorValue = try XCTUnwrap(continuationError as? E)
XCTAssertEqual(errorValue.value, 2)
}
// MARK: - JSClosure Tests
func testAsyncJSClosure() async throws {
// Test Async JSClosure
let delayClosure = JSClosure.async { _ -> JSValue in
try await Task.sleep(nanoseconds: 200_000_000)
return JSValue.number(3)
}
let delayObject = JSObject.global.Object.function!.new()
delayObject.closure = delayClosure.jsValue
let closureDiff = try await measureTime {
let promise = JSPromise(from: delayObject.closure!())
XCTAssertNotNil(promise)
let result = try await promise!.value
XCTAssertEqual(result, .number(3))
}
XCTAssertGreaterThanOrEqual(closureDiff, 200)
}
// MARK: - Clock Tests
#if compiler(>=5.7)
func testClockSleep() async throws {
// Test ContinuousClock.sleep
let continuousClockDiff = try await measureTime {
let c = ContinuousClock()
try await c.sleep(until: .now + .milliseconds(100))
}
XCTAssertGreaterThanOrEqual(continuousClockDiff, 99)
// Test SuspendingClock.sleep
let suspendingClockDiff = try await measureTime {
let c = SuspendingClock()
try await c.sleep(until: .now + .milliseconds(100))
}
XCTAssertGreaterThanOrEqual(suspendingClockDiff, 99)
}
#endif
}