-
Notifications
You must be signed in to change notification settings - Fork 0
/
CompletionCombinatorTests.kt
258 lines (246 loc) · 10.1 KB
/
CompletionCombinatorTests.kt
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
package pt.isel.pc.problemsets.set2
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import pt.isel.pc.problemsets.sync.combinator.AggregationError
import pt.isel.pc.problemsets.sync.combinator.CompletionCombinator
import pt.isel.pc.problemsets.sync.lockbased.LockBasedCompletionCombinator
import pt.isel.pc.problemsets.utils.randomTo
import java.io.IOException
import java.time.Duration
import java.time.Instant
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.stream.Stream
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertIs
import kotlin.test.assertTrue
internal class CompletionCombinatorTests {
private val errorMsg = "Expected error"
// Method: all
@ParameterizedTest(name = "{index} - {0}")
@MethodSource("implementations")
fun `Combine all future's execution`(
name: String,
compCombinator: CompletionCombinator,
executor: ScheduledExecutorService
) {
val start = Instant.now()
val nrFutures = 10 randomTo 25
val durationInMillis = 250L
var biggestDelayedDuration = 0L
var totalDuration = 0L
val futures = (1L..nrFutures).map {
val delay = it * durationInMillis
if (delay > biggestDelayedDuration) {
biggestDelayedDuration = delay
}
totalDuration += delay
delayExecution(executor, Duration.ofMillis(delay)) { true }
}
val allFutures = compCombinator.all(futures)
val result = allFutures.toCompletableFuture().get()
val delta = Duration.between(start, Instant.now())
if (executor::class == singleThreadDelayExecutor::class) {
// ensure the duration of the test should be at least the duration of all
// future delayed executions summed up if the executor is single threaded
// since the futures are executed sequentially
assertTrue(delta.toMillis() >= nrFutures * durationInMillis)
}
if (executor::class == multiThreadDelayExecutor::class) {
// ensure the duration of the test should be at least the duration of the
// biggest delayed execution and at most the duration of all future delayed
// executions summed up if the executor is multithreaded since the futures
// are executed in parallel
assertTrue(delta.toMillis() >= biggestDelayedDuration)
assertTrue(delta.toMillis() <= totalDuration)
}
assertEquals(nrFutures, result.size)
assertTrue(result.all { it })
}
@ParameterizedTest(name = "{index} - {0}")
@MethodSource("implementations")
fun `Combine all future's execution but one of the futures throws an exception`(
name: String,
compCombinator: CompletionCombinator,
executor: ScheduledExecutorService
) {
val start = Instant.now()
val nrFutures = 50 randomTo 100
val durationInMillisForError = 1000L randomTo 2000L
val futures = (1L..nrFutures).map {
delayExecution(executor) { true }
}
val errorFuture =
delayExecution<Boolean>(executor, Duration.ofMillis(durationInMillisForError)) {
throw RuntimeException(errorMsg)
}
val allFutures = compCombinator.all(futures + errorFuture)
val result = assertFailsWith<ExecutionException> {
allFutures.toCompletableFuture().get()
}
assertEquals(errorMsg, result.cause?.message)
val delta = Duration.between(start, Instant.now())
// ensure the duration of the test should be at least the duration of the
// delayed execution of the future that throws an exception.
assertTrue(delta.toMillis() >= durationInMillisForError)
}
// Method: any
@ParameterizedTest(name = "{index} - {0}")
@MethodSource("implementations")
fun `Combine any future's execution`(
name: String,
compCombinator: CompletionCombinator,
executor: ScheduledExecutorService
) {
val start = Instant.now()
val nrFutures = 50 randomTo 100
val durationInMillis = 100L randomTo 200L
val futures = (1L..nrFutures).map {
delayExecution(
executor,
Duration.ofMillis(it * durationInMillis)
) { it }
}
val future = compCombinator.any(futures)
val result = future.toCompletableFuture().get()
val delta = Duration.between(start, Instant.now())
// ensure the duration of the test should be at least the duration of the
// delayed execution of the future that completes first (which will be the
// one with the smallest delay, in this case the first one)
assertTrue { delta >= Duration.ofMillis(durationInMillis) }
assertTrue(result == 1L)
}
@ParameterizedTest(name = "{index} - {0}")
@MethodSource("implementations")
fun `Combine any future's execution but some futures throw an exception`(
name: String,
compCombinator: CompletionCombinator,
executor: ScheduledExecutorService
) {
val nrFutures = 50 randomTo 100
var successCounter = 0
var failureCounter = 0
val futures: List<CompletableFuture<Any>> = (1L..nrFutures).map {
if (it % 2 == 0L) {
delayExecution(executor) { it }
} else {
delayExecution(executor) {
throw randomThrowable
}
}
}
val future = compCombinator.any(futures)
runCatching {
future.toCompletableFuture().get()
}.onFailure {
failureCounter++
}.onSuccess {
successCounter++
}
// ensure that the future was completed with success
assertEquals(0, failureCounter)
assertEquals(1, successCounter)
}
@ParameterizedTest(name = "{index} - {0}")
@MethodSource("implementations")
fun `Combine any future's execution but all futures throw an exception`(
name: String,
compCombinator: CompletionCombinator,
executor: ScheduledExecutorService
) {
val nrFutures = 500 randomTo 1000
val listThrowables = mutableListOf<Throwable>()
val futures: List<CompletableFuture<Nothing>> = (1L..nrFutures).map {
val randomTh = randomThrowable
listThrowables.add(randomTh)
delayExecution(executor) {
throw randomTh
}
}
val future = compCombinator.any(futures)
runCatching {
future.toCompletableFuture().get()
}.onFailure {
// because it was executed inside a thread pool, the throwable is wrapped
assertIs<ExecutionException>(it)
val throwable = it.cause
// unwrap the execution exception
assertIs<AggregationError>(throwable)
assertEquals(nrFutures, throwable.throwables.size)
// ensure all throwables were catched correctly in the aggregation error list
throwable.throwables.forEach { th ->
assertContains(listThrowables, th)
}
}
}
companion object {
private val singleThreadDelayExecutor = Executors.newSingleThreadScheduledExecutor()
private val multiThreadDelayExecutor = Executors.newScheduledThreadPool(16)
private val listOfThrowables: List<Throwable> = listOf(
ArithmeticException(),
ArrayIndexOutOfBoundsException(),
NullPointerException(),
ClassCastException(),
IOException(),
OutOfMemoryError(),
StackOverflowError(),
NoSuchElementException(),
UnsupportedOperationException(),
SecurityException()
)
private val randomThrowable: Throwable
get() = listOfThrowables.random()
@JvmStatic
fun implementations(): Stream<Arguments> =
(1..5).flatMap {
listOf(
Arguments.of(
"Using ${LockBasedCompletionCombinator::class.simpleName} with single-thread executor",
LockBasedCompletionCombinator(),
Executors.newSingleThreadScheduledExecutor()
),
Arguments.of(
"Using ${LockBasedCompletionCombinator::class.simpleName} with multi-thread executor",
LockBasedCompletionCombinator(),
Executors.newScheduledThreadPool(16)
),
Arguments.of(
"Using ${LockFreeCompletionCombinator::class.simpleName} with single-thread executor",
LockFreeCompletionCombinator(),
Executors.newSingleThreadScheduledExecutor()
),
Arguments.of(
"Using ${LockFreeCompletionCombinator::class.simpleName} with multi-thread executor",
LockFreeCompletionCombinator(),
Executors.newScheduledThreadPool(16)
)
)
}.stream()
@JvmStatic
fun <T> delayExecution(
executor: ScheduledExecutorService,
duration: Duration = Duration.ofMillis(1000L),
supplier: () -> T
): CompletableFuture<T> {
val cf = CompletableFuture<T>()
executor.schedule(
{
runCatching {
cf.complete(supplier())
}.onFailure {
cf.completeExceptionally(it)
}
},
duration.toMillis(),
TimeUnit.MILLISECONDS
)
return cf
}
}
}