Skip to content

Commit

Permalink
feat(core): add a randomPort pebble function
Browse files Browse the repository at this point in the history
  • Loading branch information
tchiotludo committed Jan 21, 2025
1 parent 01a77af commit 4d074cb
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ public Map<String, Function> getFunctions() {
functions.put("errorLogs", errorLogsFunction);
}
functions.put("randomInt", new RandomIntFunction());
functions.put("randomPort", new RandomPortFunction());
return functions;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.kestra.core.runners.pebble.functions;

import io.pebbletemplates.pebble.error.PebbleException;
import io.pebbletemplates.pebble.extension.Function;
import io.pebbletemplates.pebble.template.EvaluationContext;
import io.pebbletemplates.pebble.template.PebbleTemplate;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.Map;

public class RandomPortFunction implements Function {
@Override
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
try (ServerSocket tempSocket = new ServerSocket(0)) {
return tempSocket.getLocalPort();
} catch (IOException e) {
throw new PebbleException(
e,
"Unable to get random port",
lineNumber,
self.getName()
);
}
}

@Override
public List<String> getArgumentNames() {
return List.of();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.kestra.core.runners.pebble.functions;

import io.kestra.core.exceptions.IllegalVariableEvaluationException;
import io.kestra.core.junit.annotations.KestraTest;
import io.kestra.core.runners.VariableRenderer;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import java.util.Collections;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

@KestraTest
class RandomPortFunctionTest {
@Inject VariableRenderer variableRenderer;

@Test
void checkIsDefined() throws IllegalVariableEvaluationException {
String rendered = variableRenderer.render("{{ randomPort() }}", Collections.emptyMap());
assertThat(Integer.parseInt(rendered), greaterThanOrEqualTo(0));
}
}

0 comments on commit 4d074cb

Please sign in to comment.