Debian Codegraph @

junit-jupiter-api/src/main/java/org/junit/jupiter/api/AssertTimeout.java

raw symbols SCIP
1 /*
2 * Copyright 2015-2024 the original author or authors.
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v2.0 which
6 * accompanies this distribution and is available at
7 *
8 * https://www.eclipse.org/legal/epl-v20.html
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 * {@code AssertTimeout} is a collection of utility methods that support asserting
24 * the execution of the code under test did not take longer than the timeout duration.
25 *
26 * @since 5.0
27 */
28 class AssertTimeout {
29
30 private AssertTimeout() {
31 /* no-op */
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 }