-
Notifications
You must be signed in to change notification settings - Fork 665
/
Copy pathNIOThreadPoolTaskExecutorTest.swift
81 lines (71 loc) · 2.82 KB
/
NIOThreadPoolTaskExecutorTest.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019-2025 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
import NIOTestUtils
import XCTest
class NIOThreadPoolTaskExecutorTest: XCTestCase {
struct TestError: Error {}
func runTasksSimultaneously(numberOfTasks: Int) async {
await withNIOThreadPoolTaskExecutor(numberOfThreads: numberOfTasks) { taskExecutor in
await withDiscardingTaskGroup { group in
var taskBlockers = [ConditionLock<Bool>]()
defer {
// Unblock all tasks
for taskBlocker in taskBlockers {
taskBlocker.lock()
taskBlocker.unlock(withValue: true)
}
}
for taskNumber in 1...numberOfTasks {
let taskStarted = ConditionLock(value: false)
let taskBlocker = ConditionLock(value: false)
taskBlockers.append(taskBlocker)
// Start task and block it
group.addTask(executorPreference: taskExecutor) {
taskStarted.lock()
taskStarted.unlock(withValue: true)
taskBlocker.lock(whenValue: true)
taskBlocker.unlock()
}
// Verify that task was able to start
if taskStarted.lock(whenValue: true, timeoutSeconds: 5) {
taskStarted.unlock()
} else {
XCTFail("Task \(taskNumber) failed to start.")
break
}
}
}
}
}
func testRunsTaskOnSingleThread() async {
await runTasksSimultaneously(numberOfTasks: 1)
}
func testRunsMultipleTasksOnMultipleThreads() async {
await runTasksSimultaneously(numberOfTasks: 3)
}
func testReturnsBodyResult() async {
let expectedResult = "result"
let result = await withNIOThreadPoolTaskExecutor(numberOfThreads: 1) { _ in return expectedResult }
XCTAssertEqual(result, expectedResult)
}
func testRethrows() async {
do {
try await withNIOThreadPoolTaskExecutor(numberOfThreads: 1) { _ in throw TestError() }
XCTFail("Function did not rethrow.")
} catch {
XCTAssertTrue(error is TestError)
}
}
}