Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): add a randomPort pebble function #6850

Merged
merged 1 commit into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
}
}
Loading