Debian Codegraph @

src/test/java/io/reactivex/rxjava3/core/Retry.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.core;
15
16 import org.junit.rules.TestRule;
17 import org.junit.runner.Description;
18 import org.junit.runners.model.Statement;
19
20 /**
21 * Test rule to retry flaky tests.
22 * <a href="http://stackoverflow.com/a/8301639/61158">From Stackoverflow</a>.
23 */
24 public class Retry implements TestRule {
25
26 final class RetryStatement extends Statement {
27 private final Statement base;
28 private final Description description;
29
30 RetryStatement(Statement base, Description description) {
31 this.base = base;
32 this.description = description;
33 }
34
35 @Override
36 public void evaluate() throws Throwable {
37 Throwable caughtThrowable = null;
38
39 for (int i = 0; i < retryCount; i++) {
40 try {
41 base.evaluate();
42 return;
43 } catch (Throwable t) {
44 caughtThrowable = t;
45 System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed");
46 int n = sleep;
47 if (backoff && i != 0) {
48 n = n * (2 << i);
49 }
50 Thread.sleep(n);
51 }
52 }
53 System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures");
54 throw caughtThrowable;
55 }
56 }
57
58 final int retryCount;
59
60 final int sleep;
61
62 final boolean backoff;
63
64 public Retry(int retryCount, int sleep, boolean backoff) {
65 this.retryCount = retryCount;
66 this.sleep = sleep;
67 this.backoff = backoff;
68 }
69
70 @Override
71 public Statement apply(Statement base, Description description) {
72 return statement(base, description);
73 }
74
75 private Statement statement(final Statement base, final Description description) {
76 return new RetryStatement(base, description);
77 }
78 }