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 6256638 commit 91c0c21
Show file tree
Hide file tree
Showing 2 changed files with 37 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
36 changes: 36 additions & 0 deletions src/test/java/io/github/pixee/security/ExecuteWithTimeoutTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.github.pixee.security;

import org.junit.jupiter.api.Test;

import java.util.regex.Matcher;
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(){
Pattern pat = Pattern.compile("string");
String input = "some very long string";
Matcher matcher = pat.matcher(input);
boolean result = ExecuteWithTimeout.executeWithTimeout(() -> matcher.find(), 5000);
assertThat(result, is(equalTo(true)));
}

@Test
void it_throws_exception_due_to_timeout(){
Pattern pat = Pattern.compile("string");
String input = "some very long string";
Matcher matcher = pat.matcher(input);
RuntimeException exception = assertThrows(
RuntimeException.class,
() -> ExecuteWithTimeout.executeWithTimeout(() -> matcher.find(), 0)
);
assertThat(exception.getMessage(), is(equalTo("Failed to execute within time limit.")));
}

}

0 comments on commit 91c0c21

Please sign in to comment.