File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
main/kotlin/com/github/michaelbull/retry/policy
test/kotlin/com/github/michaelbull/retry/policy Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com.github.michaelbull.retry.policy
2
+
3
+ import com.github.michaelbull.retry.ContinueRetrying
4
+ import com.github.michaelbull.retry.RetryFailure
5
+ import com.github.michaelbull.retry.RetryInstruction
6
+ import com.github.michaelbull.retry.StopRetrying
7
+
8
+ /* *
9
+ * Creates a [RetryPolicy] that returns an [instruction][RetryInstruction] to
10
+ * [ContinueRetrying] if the [RetryFailure] satisfies the given [predicate],
11
+ * or an [instruction][RetryInstruction] to [StopRetrying] if it doesn't.
12
+ */
13
+ inline fun <E > retryIf (crossinline predicate : RetryFailure <E >.() -> Boolean ): RetryPolicy <E > = {
14
+ if (predicate(this )) {
15
+ ContinueRetrying
16
+ } else {
17
+ StopRetrying
18
+ }
19
+ }
Original file line number Diff line number Diff line change
1
+ package com.github.michaelbull.retry.policy
2
+
3
+ import com.github.michaelbull.retry.retry
4
+ import kotlinx.coroutines.ExperimentalCoroutinesApi
5
+ import kotlinx.coroutines.test.runBlockingTest
6
+ import org.junit.jupiter.api.Assertions.assertEquals
7
+ import org.junit.jupiter.api.Test
8
+ import org.junit.jupiter.api.assertThrows
9
+
10
+ @ExperimentalCoroutinesApi
11
+ class RetryIfTest {
12
+
13
+ private val retryIllegalState = retryIf<Throwable > {
14
+ reason is IllegalStateException
15
+ }
16
+
17
+ @Test
18
+ fun `retry with filter should retry specified exception` () = runBlockingTest {
19
+ var attempts = 0
20
+
21
+ retry(limitAttempts(5 ) + retryIllegalState) {
22
+ attempts++
23
+ if (attempts < 5 ) {
24
+ throw IllegalStateException ()
25
+ }
26
+ }
27
+
28
+ assertEquals(5 , attempts)
29
+ }
30
+
31
+ @Test
32
+ fun `retry with filter should not retry unspecified exception` () = runBlockingTest {
33
+ var attempts = 0
34
+
35
+ assertThrows<UnsupportedOperationException > {
36
+ retry(limitAttempts(5 ) + retryIllegalState) {
37
+ attempts++
38
+ if (attempts < 5 ) {
39
+ throw UnsupportedOperationException ()
40
+ }
41
+ }
42
+ }
43
+
44
+ assertEquals(1 , attempts)
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments