-
Notifications
You must be signed in to change notification settings - Fork 111
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
64 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
cloudinary-test-common/src/main/java/com/cloudinary/test/rules/RetryRule.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package com.cloudinary.test.rules; | ||
|
||
import org.junit.rules.TestRule; | ||
import org.junit.runner.Description; | ||
import org.junit.runners.model.Statement; | ||
|
||
import java.util.Objects; | ||
|
||
public class RetryRule implements TestRule { | ||
private int retryCount; | ||
private int delay; | ||
|
||
public RetryRule(int retryCount, int delay) { | ||
this.retryCount = retryCount; | ||
this.delay = delay; | ||
} | ||
|
||
public RetryRule() { | ||
this.retryCount = 3; | ||
this.delay = 3; | ||
} | ||
|
||
public Statement apply(Statement base, Description description) { | ||
return statement(base, description); | ||
} | ||
|
||
private Statement statement(final Statement base, final Description description) { | ||
return new Statement() { | ||
@Override | ||
public void evaluate() throws Throwable { | ||
Throwable caughtThrowable = null; | ||
for (int i = 0; i < retryCount; i++) { | ||
try { | ||
base.evaluate(); | ||
return; | ||
} catch (Throwable t) { | ||
caughtThrowable = t; | ||
System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed."); | ||
Thread.sleep(delay * 1000); | ||
} | ||
} | ||
System.err.println(description.getDisplayName() + ": Giving up after " + retryCount + " failures."); | ||
throw Objects.requireNonNull(caughtThrowable); | ||
} | ||
}; | ||
} | ||
} |