diff --git a/src/main/java/io/github/pixee/security/ExecuteWithTimeout.java b/src/main/java/io/github/pixee/security/ExecuteWithTimeout.java index dcf0f78..35643f0 100644 --- a/src/main/java/io/github/pixee/security/ExecuteWithTimeout.java +++ b/src/main/java/io/github/pixee/security/ExecuteWithTimeout.java @@ -14,7 +14,7 @@ public class ExecuteWithTimeout{ /** * Tries to execute a given {@link Callable} within a given timeout in milliseconds. Returns the result if successful, otherwise throws a {@link RuntimeException}. */ - public E executeWithTimeout(final Callable action, final int timeout) { + public static E executeWithTimeout(final Callable action, final int timeout) { Future maybeResult = Executors.newSingleThreadExecutor().submit(action); try { return maybeResult.get(timeout, TimeUnit.MILLISECONDS); diff --git a/src/test/java/io/github/pixee/security/ExecuteWithinTimeoutTest.java b/src/test/java/io/github/pixee/security/ExecuteWithinTimeoutTest.java new file mode 100644 index 0000000..d86ed65 --- /dev/null +++ b/src/test/java/io/github/pixee/security/ExecuteWithinTimeoutTest.java @@ -0,0 +1,31 @@ +package io.github.pixee.security; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +final class ExecuteWithTimeoutTest { + + @Test + void it_executes_within_timeout_and_returns(){ + var pat = Pattern.compile("string"); + String input = "some very long string"; + var matcher = pat.matcher(input); + boolean result = ExecuteWithTimeout.executeWithTimeout(() -> matcher.matches(), 5000); + assertThat(result, is(true)); + } + + @Test + void it_throws_exception_due_to_timeout(){ + assertThrows( + RuntimeException.class, + () -> ExecuteWithTimeout.executeWithTimeout(() -> matcher.matches(), 0) + ); + } + +}