| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
package org.junit.jupiter.api; |
| 12 |
|
| 13 |
import static org.junit.jupiter.api.AssertionFailureBuilder.assertionFailure; |
| 14 |
import static org.junit.platform.commons.util.ExceptionUtils.throwAsUncheckedException; |
| 15 |
|
| 16 |
import java.time.Duration; |
| 17 |
import java.util.function.Supplier; |
| 18 |
|
| 19 |
import org.junit.jupiter.api.function.Executable; |
| 20 |
import org.junit.jupiter.api.function.ThrowingSupplier; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
class AssertTimeout { |
| 29 |
|
| 30 |
private AssertTimeout() { |
| 31 |
|
| 32 |
} |
| 33 |
|
| 34 |
static void assertTimeout(Duration timeout, Executable executable) { |
| 35 |
assertTimeout(timeout, executable, (String) null); |
| 36 |
} |
| 37 |
|
| 38 |
static void assertTimeout(Duration timeout, Executable executable, String message) { |
| 39 |
assertTimeout(timeout, () -> { |
| 40 |
executable.execute(); |
| 41 |
return null; |
| 42 |
}, message); |
| 43 |
} |
| 44 |
|
| 45 |
static void assertTimeout(Duration timeout, Executable executable, Supplier<String> messageSupplier) { |
| 46 |
assertTimeout(timeout, () -> { |
| 47 |
executable.execute(); |
| 48 |
return null; |
| 49 |
}, messageSupplier); |
| 50 |
} |
| 51 |
|
| 52 |
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier) { |
| 53 |
return assertTimeout(timeout, supplier, (Object) null); |
| 54 |
} |
| 55 |
|
| 56 |
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, String message) { |
| 57 |
return assertTimeout(timeout, supplier, (Object) message); |
| 58 |
} |
| 59 |
|
| 60 |
static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, Supplier<String> messageSupplier) { |
| 61 |
return assertTimeout(timeout, supplier, (Object) messageSupplier); |
| 62 |
} |
| 63 |
|
| 64 |
private static <T> T assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, Object messageOrSupplier) { |
| 65 |
long timeoutInMillis = timeout.toMillis(); |
| 66 |
long start = System.currentTimeMillis(); |
| 67 |
T result = null; |
| 68 |
try { |
| 69 |
result = supplier.get(); |
| 70 |
} |
| 71 |
catch (Throwable ex) { |
| 72 |
throwAsUncheckedException(ex); |
| 73 |
} |
| 74 |
|
| 75 |
long timeElapsed = System.currentTimeMillis() - start; |
| 76 |
if (timeElapsed > timeoutInMillis) { |
| 77 |
assertionFailure() |
| 78 |
.message(messageOrSupplier) |
| 79 |
.reason("execution exceeded timeout of " + timeoutInMillis + " ms by " |
| 80 |
+ (timeElapsed - timeoutInMillis) + " ms") |
| 81 |
.buildAndThrow(); |
| 82 |
} |
| 83 |
return result; |
| 84 |
} |
| 85 |
|
| 86 |
} |