Skip to content

Commit

Permalink
Added test
Browse files Browse the repository at this point in the history
  • Loading branch information
andrecsilva committed Dec 17, 2024
1 parent c54155e commit 5264118
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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> E executeWithTimeout(final Callable<E> action, final int timeout) {
public static <E> E executeWithTimeout(final Callable<E> action, final int timeout) {
Future<E> maybeResult = Executors.newSingleThreadExecutor().submit(action);
try {
return maybeResult.get(timeout, TimeUnit.MILLISECONDS);
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
);
}

}

0 comments on commit 5264118

Please sign in to comment.