feat(Unit Tests) #8171 convert hamcrest to assertj (#8276)

* feat(Unit Tests) #8171 convert hamcrest to assertj

* fix(Unit Tests) #8171 failing unit test after assertj migration

---------

Co-authored-by: nKwiatkowski <nkwiatkowski@kestra.io>
This commit is contained in:
Nicolas K.
2025-04-08 15:48:54 +02:00
committed by GitHub
parent cc5a1c9f68
commit 5285bea930
320 changed files with 4714 additions and 5257 deletions

View File

@@ -196,6 +196,9 @@ subprojects {
testImplementation 'org.hamcrest:hamcrest' testImplementation 'org.hamcrest:hamcrest'
testImplementation 'org.hamcrest:hamcrest-library' testImplementation 'org.hamcrest:hamcrest-library'
testImplementation 'org.exparity:hamcrest-date' testImplementation 'org.exparity:hamcrest-date'
//assertj
testImplementation 'org.assertj:assertj-core'
} }
test { test {

View File

@@ -13,8 +13,7 @@ import picocli.CommandLine;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
class AppTest { class AppTest {
@@ -26,7 +25,7 @@ class AppTest {
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
PicocliRunner.call(App.class, ctx, "--help"); PicocliRunner.call(App.class, ctx, "--help");
assertThat(out.toString(), containsString("kestra")); assertThat(out.toString()).contains("kestra");
} }
} }
@@ -42,7 +41,7 @@ class AppTest {
new CommandLine(App.class, new MicronautFactory(ctx)).execute(args); new CommandLine(App.class, new MicronautFactory(ctx)).execute(args);
assertTrue(ctx.getProperty("kestra.server-type", ServerType.class).isEmpty()); assertTrue(ctx.getProperty("kestra.server-type", ServerType.class).isEmpty());
assertThat(out.toString(), startsWith("Usage: kestra server " + serverType)); assertThat(out.toString()).startsWith("Usage: kestra server " + serverType);
} }
} }
@@ -56,9 +55,9 @@ class AppTest {
try (ApplicationContext ctx = App.applicationContext(App.class, argsWithMissingParams)) { try (ApplicationContext ctx = App.applicationContext(App.class, argsWithMissingParams)) {
new CommandLine(App.class, new MicronautFactory(ctx)).execute(argsWithMissingParams); new CommandLine(App.class, new MicronautFactory(ctx)).execute(argsWithMissingParams);
assertThat(out.toString(), startsWith("Missing required parameters: ")); assertThat(out.toString()).startsWith("Missing required parameters: ");
assertThat(out.toString(), containsString("Usage: kestra flow namespace update ")); assertThat(out.toString()).contains("Usage: kestra flow namespace update ");
assertThat(out.toString(), not(containsString("MissingParameterException: "))); assertThat(out.toString()).doesNotContain("MissingParameterException: ");
} }
} }
} }

View File

@@ -8,8 +8,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class ServerCommandValidatorTest { class ServerCommandValidatorTest {
@@ -40,8 +39,8 @@ class ServerCommandValidatorTest {
.start() .start()
); );
final Throwable rootException = getRootException(exception); final Throwable rootException = getRootException(exception);
assertThat(rootException.getClass(), is(ServerCommandValidator.ServerCommandException.class)); assertThat(rootException.getClass()).isEqualTo(ServerCommandValidator.ServerCommandException.class);
assertThat(rootException.getMessage(), is("Incomplete server configuration - missing required properties")); assertThat(rootException.getMessage()).isEqualTo("Incomplete server configuration - missing required properties");
} }
private Throwable getRootException(Throwable exception) { private Throwable getRootException(Throwable exception) {

View File

@@ -8,8 +8,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
class ConfigPropertiesCommandTest { class ConfigPropertiesCommandTest {
@Test @Test
@@ -20,8 +19,8 @@ class ConfigPropertiesCommandTest {
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
PicocliRunner.call(ConfigPropertiesCommand.class, ctx); PicocliRunner.call(ConfigPropertiesCommand.class, ctx);
assertThat(out.toString(), containsString("activeEnvironments:")); assertThat(out.toString()).contains("activeEnvironments:");
assertThat(out.toString(), containsString("- test")); assertThat(out.toString()).contains("- test");
} }
} }
} }

View File

@@ -11,9 +11,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class FlowCreateOrUpdateCommandTest { class FlowCreateOrUpdateCommandTest {
@RetryingTest(5) // flaky on CI but cannot be reproduced even with 100 repetitions @RetryingTest(5) // flaky on CI but cannot be reproduced even with 100 repetitions
@@ -38,7 +36,7 @@ class FlowCreateOrUpdateCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("4 flow(s)")); assertThat(out.toString()).contains("4 flow(s)");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -53,7 +51,7 @@ class FlowCreateOrUpdateCommandTest {
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
// 2 delete + 1 update // 2 delete + 1 update
assertThat(out.toString(), containsString("4 flow(s)")); assertThat(out.toString()).contains("4 flow(s)");
} }
} }
@@ -80,7 +78,7 @@ class FlowCreateOrUpdateCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("4 flow(s)")); assertThat(out.toString()).contains("4 flow(s)");
out.reset(); out.reset();
// no "delete" arg should behave as no-delete // no "delete" arg should behave as no-delete
@@ -93,7 +91,7 @@ class FlowCreateOrUpdateCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -106,7 +104,7 @@ class FlowCreateOrUpdateCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
@@ -131,8 +129,8 @@ class FlowCreateOrUpdateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
} }

View File

@@ -9,9 +9,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class FlowDotCommandTest { class FlowDotCommandTest {
@Test @Test
@@ -26,8 +24,8 @@ class FlowDotCommandTest {
}; };
Integer call = PicocliRunner.call(FlowDotCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowDotCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("\"root.date\"[shape=box];")); assertThat(out.toString()).contains("\"root.date\"[shape=box];");
} }
} }
} }

View File

@@ -7,8 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
class FlowExpandCommandTest { class FlowExpandCommandTest {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -23,22 +22,20 @@ class FlowExpandCommandTest {
}; };
Integer call = PicocliRunner.call(FlowExpandCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowExpandCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), is( assertThat(out.toString()).isEqualTo("id: include\n" +
"id: include\n" + "namespace: io.kestra.cli\n" +
"namespace: io.kestra.cli\n" + "\n" +
"\n" + "# The list of tasks\n" +
"# The list of tasks\n" + "tasks:\n" +
"tasks:\n" + "- id: t1\n" +
"- id: t1\n" + " type: io.kestra.plugin.core.debug.Return\n" +
" type: io.kestra.plugin.core.debug.Return\n" + " format: \"Lorem ipsum dolor sit amet\"\n" +
" format: \"Lorem ipsum dolor sit amet\"\n" + "- id: t2\n" +
"- id: t2\n" + " type: io.kestra.plugin.core.debug.Return\n" +
" type: io.kestra.plugin.core.debug.Return\n" + " format: |\n" +
" format: |\n" + " Lorem ipsum dolor sit amet\n" +
" Lorem ipsum dolor sit amet\n" + " Lorem ipsum dolor sit amet\n");
" Lorem ipsum dolor sit amet\n"
));
} }
} }
} }

View File

@@ -14,10 +14,7 @@ import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class FlowExportCommandTest { class FlowExportCommandTest {
@Test @Test
@@ -42,7 +39,7 @@ class FlowExportCommandTest {
directory.getPath(), directory.getPath(),
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, updateArgs); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, updateArgs);
assertThat(out.toString(), containsString("3 flow(s)")); assertThat(out.toString()).contains("3 flow(s)");
// then we export them // then we export them
String[] exportArgs = { String[] exportArgs = {
@@ -58,11 +55,11 @@ class FlowExportCommandTest {
}; };
PicocliRunner.call(FlowExportCommand.class, ctx, exportArgs); PicocliRunner.call(FlowExportCommand.class, ctx, exportArgs);
File file = new File("/tmp/flows.zip"); File file = new File("/tmp/flows.zip");
assertThat(file.exists(), is(true)); assertThat(file.exists()).isEqualTo(true);
ZipFile zipFile = new ZipFile(file); ZipFile zipFile = new ZipFile(file);
// When launching the test in a suite, there is 4 flows but when lauching individualy there is only 3 // When launching the test in a suite, there is 4 flows but when lauching individualy there is only 3
assertThat(zipFile.stream().count(), greaterThanOrEqualTo(3L)); assertThat(zipFile.stream().count()).isGreaterThanOrEqualTo(3L);
file.delete(); file.delete();
} }

View File

@@ -10,9 +10,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class FlowUpdatesCommandTest { class FlowUpdatesCommandTest {
@Test @Test
@@ -39,7 +37,7 @@ class FlowUpdatesCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("successfully updated !")); assertThat(out.toString()).contains("successfully updated !");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -56,7 +54,7 @@ class FlowUpdatesCommandTest {
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
// 2 delete + 1 update // 2 delete + 1 update
assertThat(out.toString(), containsString("successfully updated !")); assertThat(out.toString()).contains("successfully updated !");
} }
} }
@@ -85,7 +83,7 @@ class FlowUpdatesCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("4 flow(s)")); assertThat(out.toString()).contains("4 flow(s)");
out.reset(); out.reset();
// no "delete" arg should behave as no-delete // no "delete" arg should behave as no-delete
@@ -100,7 +98,7 @@ class FlowUpdatesCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -115,7 +113,7 @@ class FlowUpdatesCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
@@ -144,7 +142,7 @@ class FlowUpdatesCommandTest {
}; };
PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(out.toString(), containsString("Invalid entity: flow.namespace: io.kestra.outsider_quattro_-1 - flow namespace is invalid")); assertThat(out.toString()).contains("Invalid entity: flow.namespace: io.kestra.outsider_quattro_-1 - flow namespace is invalid");
} }
} }
@@ -171,8 +169,8 @@ class FlowUpdatesCommandTest {
}; };
Integer call = PicocliRunner.call(FlowUpdatesCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowUpdatesCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class FlowValidateCommandTest { class FlowValidateCommandTest {
@Test @Test
@@ -24,8 +22,8 @@ class FlowValidateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("✓ - io.kestra.cli / include")); assertThat(out.toString()).contains("✓ - io.kestra.cli / include");
} }
} }
@@ -41,10 +39,10 @@ class FlowValidateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("✓ - system / warning")); assertThat(out.toString()).contains("✓ - system / warning");
assertThat(out.toString(), containsString("⚠ - tasks[0] is deprecated")); assertThat(out.toString()).contains("⚠ - tasks[0] is deprecated");
assertThat(out.toString(), containsString(" - io.kestra.core.tasks.log.Log is replaced by io.kestra.plugin.core.log.Log")); assertThat(out.toString()).contains(" - io.kestra.core.tasks.log.Log is replaced by io.kestra.plugin.core.log.Log");
} }
} }
} }

View File

@@ -10,8 +10,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
public class SingleFlowCommandsTest { public class SingleFlowCommandsTest {
@@ -37,7 +36,7 @@ public class SingleFlowCommandsTest {
}; };
PicocliRunner.call(FlowDeleteCommand.class, ctx, deleteArgs); PicocliRunner.call(FlowDeleteCommand.class, ctx, deleteArgs);
assertThat(out.toString(), containsString("Flow successfully deleted !")); assertThat(out.toString()).contains("Flow successfully deleted !");
out.reset(); out.reset();
String[] createArgs = { String[] createArgs = {
@@ -49,7 +48,7 @@ public class SingleFlowCommandsTest {
}; };
PicocliRunner.call(FlowCreateCommand.class, ctx, createArgs); PicocliRunner.call(FlowCreateCommand.class, ctx, createArgs);
assertThat(out.toString(), containsString("Flow successfully created !")); assertThat(out.toString()).contains("Flow successfully created !");
out.reset();String[] updateArgs = { out.reset();String[] updateArgs = {
@@ -63,7 +62,7 @@ public class SingleFlowCommandsTest {
}; };
PicocliRunner.call(FlowUpdateCommand.class, ctx, updateArgs); PicocliRunner.call(FlowUpdateCommand.class, ctx, updateArgs);
assertThat(out.toString(), containsString("Flow successfully updated !")); assertThat(out.toString()).contains("Flow successfully updated !");
out.reset(); out.reset();
} }
} }

View File

@@ -10,9 +10,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class TemplateValidateCommandTest { class TemplateValidateCommandTest {
@Test @Test
@@ -28,9 +26,9 @@ class TemplateValidateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args);
assertThat(call, is(1)); assertThat(call).isEqualTo(1);
assertThat(out.toString(), containsString("Unable to parse flow")); assertThat(out.toString()).contains("Unable to parse flow");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
@@ -56,9 +54,9 @@ class TemplateValidateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args);
assertThat(call, is(1)); assertThat(call).isEqualTo(1);
assertThat(out.toString(), containsString("Unable to parse flow")); assertThat(out.toString()).contains("Unable to parse flow");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class FlowNamespaceCommandTest { class FlowNamespaceCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class FlowNamespaceCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(FlowNamespaceCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowNamespaceCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra flow namespace")); assertThat(out.toString()).contains("Usage: kestra flow namespace");
} }
} }
} }

View File

@@ -10,10 +10,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.Is.is;
class FlowNamespaceUpdateCommandTest { class FlowNamespaceUpdateCommandTest {
@Test @Test
@@ -39,7 +36,7 @@ class FlowNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("namespace 'io.kestra.cli' successfully updated")); assertThat(out.toString()).contains("namespace 'io.kestra.cli' successfully updated");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -55,7 +52,7 @@ class FlowNamespaceUpdateCommandTest {
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
// 2 delete + 1 update // 2 delete + 1 update
assertThat(out.toString(), containsString("namespace 'io.kestra.cli' successfully updated")); assertThat(out.toString()).contains("namespace 'io.kestra.cli' successfully updated");
} }
} }
@@ -81,9 +78,9 @@ class FlowNamespaceUpdateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(call, is(1)); assertThat(call).isEqualTo(1);
assertThat(out.toString(), containsString("Unable to parse flows")); assertThat(out.toString()).contains("Unable to parse flows");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
@@ -111,7 +108,7 @@ class FlowNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("3 flow(s)")); assertThat(out.toString()).contains("3 flow(s)");
out.reset(); out.reset();
// no "delete" arg should behave as no-delete // no "delete" arg should behave as no-delete
@@ -125,7 +122,7 @@ class FlowNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
out.reset(); out.reset();
args = new String[]{ args = new String[]{
@@ -139,7 +136,7 @@ class FlowNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
@@ -165,8 +162,8 @@ class FlowNamespaceUpdateCommandTest {
}; };
Integer call = PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); Integer call = PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("1 flow(s)")); assertThat(out.toString()).contains("1 flow(s)");
} }
} }
@@ -195,8 +192,8 @@ class FlowNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("io.kestra.override")); assertThat(out.toString()).contains("io.kestra.override");
assertThat(out.toString(), not(containsString("io.kestra.cli"))); assertThat(out.toString()).doesNotContain("io.kestra.cli");
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class NamespaceCommandTest { class NamespaceCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class NamespaceCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(NamespaceCommand.class, ctx, args); Integer call = PicocliRunner.call(NamespaceCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra namespace")); assertThat(out.toString()).contains("Usage: kestra namespace");
} }
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class NamespaceFilesCommandTest { class NamespaceFilesCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class NamespaceFilesCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(NamespaceFilesCommand.class, ctx, args); Integer call = PicocliRunner.call(NamespaceFilesCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra namespace files")); assertThat(out.toString()).contains("Usage: kestra namespace files");
} }
} }
} }

View File

@@ -14,8 +14,8 @@ import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.StringContains.containsString;
class NamespaceFilesUpdateCommandTest { class NamespaceFilesUpdateCommandTest {
@Test @Test

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class KvCommandTest { class KvCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class KvCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(KvCommand.class, ctx, args); Integer call = PicocliRunner.call(KvCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra namespace kv")); assertThat(out.toString()).contains("Usage: kestra namespace kv");
} }
} }
} }

View File

@@ -16,8 +16,7 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class KvUpdateCommandTest { class KvUpdateCommandTest {
@Test @Test
@@ -43,8 +42,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("string").get(), is(new KVValue("stringValue"))); assertThat(kvStore.getValue("string").get()).isEqualTo(new KVValue("stringValue"));
assertThat(((InternalKVStore)kvStore).getRawValue("string").get(), is("\"stringValue\"")); assertThat(((InternalKVStore) kvStore).getRawValue("string").get()).isEqualTo("\"stringValue\"");
} }
} }
@@ -71,8 +70,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("int").get(), is(new KVValue(1))); assertThat(kvStore.getValue("int").get()).isEqualTo(new KVValue(1));
assertThat(((InternalKVStore)kvStore).getRawValue("int").get(), is("1")); assertThat(((InternalKVStore) kvStore).getRawValue("int").get()).isEqualTo("1");
} }
} }
@@ -101,8 +100,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("intStr").get(), is(new KVValue("1"))); assertThat(kvStore.getValue("intStr").get()).isEqualTo(new KVValue("1"));
assertThat(((InternalKVStore)kvStore).getRawValue("intStr").get(), is("\"1\"")); assertThat(((InternalKVStore) kvStore).getRawValue("intStr").get()).isEqualTo("\"1\"");
} }
} }
@@ -129,8 +128,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("object").get(), is(new KVValue(Map.of("some", "json")))); assertThat(kvStore.getValue("object").get()).isEqualTo(new KVValue(Map.of("some", "json")));
assertThat(((InternalKVStore)kvStore).getRawValue("object").get(), is("{some:\"json\"}")); assertThat(((InternalKVStore) kvStore).getRawValue("object").get()).isEqualTo("{some:\"json\"}");
} }
} }
@@ -159,8 +158,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("objectStr").get(), is(new KVValue("{\"some\":\"json\"}"))); assertThat(kvStore.getValue("objectStr").get()).isEqualTo(new KVValue("{\"some\":\"json\"}"));
assertThat(((InternalKVStore)kvStore).getRawValue("objectStr").get(), is("\"{\\\"some\\\":\\\"json\\\"}\"")); assertThat(((InternalKVStore) kvStore).getRawValue("objectStr").get()).isEqualTo("\"{\\\"some\\\":\\\"json\\\"}\"");
} }
} }
@@ -193,8 +192,8 @@ class KvUpdateCommandTest {
KVStoreService kvStoreService = ctx.getBean(KVStoreService.class); KVStoreService kvStoreService = ctx.getBean(KVStoreService.class);
KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null); KVStore kvStore = kvStoreService.get(null, "io.kestra.cli", null);
assertThat(kvStore.getValue("objectFromFile").get(), is(new KVValue(Map.of("some", "json", "from", "file")))); assertThat(kvStore.getValue("objectFromFile").get()).isEqualTo(new KVValue(Map.of("some", "json", "from", "file")));
assertThat(((InternalKVStore)kvStore).getRawValue("objectFromFile").get(), is("{some:\"json\",from:\"file\"}")); assertThat(((InternalKVStore) kvStore).getRawValue("objectFromFile").get()).isEqualTo("{some:\"json\",from:\"file\"}");
} }
} }
} }

View File

@@ -8,8 +8,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
class PluginCommandTest { class PluginCommandTest {
@@ -21,7 +20,7 @@ class PluginCommandTest {
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
PicocliRunner.call(PluginCommand.class, ctx); PicocliRunner.call(PluginCommand.class, ctx);
assertThat(out.toString(), containsString("Usage: kestra plugins")); assertThat(out.toString()).contains("Usage: kestra plugins");
} }
} }
} }

View File

@@ -17,8 +17,7 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
class PluginDocCommandTest { class PluginDocCommandTest {
@@ -44,16 +43,16 @@ class PluginDocCommandTest {
List<Path> files = Files.list(docPath).toList(); List<Path> files = Files.list(docPath).toList();
assertThat(files.size(), is(1)); assertThat(files.size()).isEqualTo(1);
assertThat(files.getFirst().getFileName().toString(), is("plugin-template-test")); assertThat(files.getFirst().getFileName().toString()).isEqualTo("plugin-template-test");
var directory = files.getFirst().toFile(); var directory = files.getFirst().toFile();
assertThat(directory.isDirectory(), is(true)); assertThat(directory.isDirectory()).isEqualTo(true);
assertThat(directory.listFiles().length, is(3)); assertThat(directory.listFiles().length).isEqualTo(3);
var readme = directory.toPath().resolve("index.md"); var readme = directory.toPath().resolve("index.md");
var readmeContent = new String(Files.readAllBytes(readme)); var readmeContent = new String(Files.readAllBytes(readme));
assertThat(readmeContent, containsString(""" assertThat(readmeContent).contains("""
--- ---
title: Template test title: Template test
description: "Plugin template for Kestra" description: "Plugin template for Kestra"
@@ -61,18 +60,17 @@ class PluginDocCommandTest {
--- ---
# Template test # Template test
""")); """);
assertThat(readmeContent, containsString(""" assertThat(readmeContent).contains("""
Plugin template for Kestra Plugin template for Kestra
This is a more complex description of the plugin. This is a more complex description of the plugin.
This is in markdown and will be inline inside the plugin page. This is in markdown and will be inline inside the plugin page.
""")); """);
assertThat(readmeContent, containsString( assertThat(readmeContent).contains("""
"""
/> Subgroup title /> Subgroup title
Subgroup description Subgroup description
@@ -89,20 +87,20 @@ class PluginDocCommandTest {
\s \s
* [Reporting](./guides/reporting.md) * [Reporting](./guides/reporting.md)
\s \s
""")); """);
// check @PluginProperty from an interface // check @PluginProperty from an interface
var task = directory.toPath().resolve("tasks/io.kestra.plugin.templates.ExampleTask.md"); var task = directory.toPath().resolve("tasks/io.kestra.plugin.templates.ExampleTask.md");
String taskDoc = new String(Files.readAllBytes(task)); String taskDoc = new String(Files.readAllBytes(task));
assertThat(taskDoc, containsString(""" assertThat(taskDoc).contains("""
### `example` ### `example`
* **Type:** ==string== * **Type:** ==string==
* **Dynamic:** ✔️ * **Dynamic:** ✔️
* **Required:** ❌ * **Required:** ❌
**Example interface** **Example interface**
""")); """);
assertThat(taskDoc, containsString(""" assertThat(taskDoc).contains("""
### `from` ### `from`
* **Type:** * **Type:**
* ==string== * ==string==
@@ -110,12 +108,12 @@ class PluginDocCommandTest {
* [==Example==](#io.kestra.core.models.annotations.example) * [==Example==](#io.kestra.core.models.annotations.example)
* **Dynamic:** ✔️ * **Dynamic:** ✔️
* **Required:** ✔️ * **Required:** ✔️
""")); """);
var authenticationGuide = directory.toPath().resolve("guides/authentication.md"); var authenticationGuide = directory.toPath().resolve("guides/authentication.md");
assertThat(new String(Files.readAllBytes(authenticationGuide)), containsString("This is how to authenticate for this plugin:")); assertThat(new String(Files.readAllBytes(authenticationGuide))).contains("This is how to authenticate for this plugin:");
var reportingGuide = directory.toPath().resolve("guides/reporting.md"); var reportingGuide = directory.toPath().resolve("guides/reporting.md");
assertThat(new String(Files.readAllBytes(reportingGuide)), containsString("This is the reporting of the plugin:")); assertThat(new String(Files.readAllBytes(reportingGuide))).contains("This is the reporting of the plugin:");
} }
} }
} }

View File

@@ -10,8 +10,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
class PluginInstallCommandTest { class PluginInstallCommandTest {
@@ -26,8 +25,8 @@ class PluginInstallCommandTest {
List<Path> files = Files.list(pluginsPath).toList(); List<Path> files = Files.list(pluginsPath).toList();
assertThat(files.size(), is(1)); assertThat(files.size()).isEqualTo(1);
assertThat(files.getFirst().getFileName().toString(), is("io_kestra_plugin__plugin-notifications__0_6_0.jar")); assertThat(files.getFirst().getFileName().toString()).isEqualTo("io_kestra_plugin__plugin-notifications__0_6_0.jar");
} }
} }
@@ -42,9 +41,9 @@ class PluginInstallCommandTest {
List<Path> files = Files.list(pluginsPath).toList(); List<Path> files = Files.list(pluginsPath).toList();
assertThat(files.size(), is(1)); assertThat(files.size()).isEqualTo(1);
assertThat(files.getFirst().getFileName().toString(), startsWith("io_kestra_plugin__plugin-notifications__")); assertThat(files.getFirst().getFileName().toString()).startsWith("io_kestra_plugin__plugin-notifications__");
assertThat(files.getFirst().getFileName().toString(), not(containsString("LATEST"))); assertThat(files.getFirst().getFileName().toString()).doesNotContain("LATEST");
} }
} }
@@ -60,8 +59,8 @@ class PluginInstallCommandTest {
List<Path> files = Files.list(pluginsPath).toList(); List<Path> files = Files.list(pluginsPath).toList();
assertThat(files.size(), is(1)); assertThat(files.size()).isEqualTo(1);
assertThat(files.getFirst().getFileName().toString(), is("io_kestra_storage__storage-s3__0_12_1.jar")); assertThat(files.getFirst().getFileName().toString()).isEqualTo("io_kestra_storage__storage-s3__0_12_1.jar");
} }
} }
} }

View File

@@ -16,8 +16,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Objects; import java.util.Objects;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
class PluginListCommandTest { class PluginListCommandTest {
@@ -41,7 +40,7 @@ class PluginListCommandTest {
String[] args = {"--plugins", pluginsPath.toAbsolutePath().toString()}; String[] args = {"--plugins", pluginsPath.toAbsolutePath().toString()};
PicocliRunner.call(PluginListCommand.class, ctx, args); PicocliRunner.call(PluginListCommand.class, ctx, args);
assertThat(out.toString(), containsString("io.kestra.plugin.templates.Example")); assertThat(out.toString()).contains("io.kestra.plugin.templates.Example");
} }
} }
} }

View File

@@ -13,8 +13,7 @@ import java.io.PrintStream;
import java.util.Map; import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@WireMockTest(httpPort = 28181) @WireMockTest(httpPort = 28181)
class PluginSearchCommandTest { class PluginSearchCommandTest {
@@ -61,9 +60,9 @@ class PluginSearchCommandTest {
PicocliRunner.call(PluginSearchCommand.class, ctx, args); PicocliRunner.call(PluginSearchCommand.class, ctx, args);
String output = outputStreamCaptor.toString().trim(); String output = outputStreamCaptor.toString().trim();
assertThat(output, containsString("Found 1 plugins matching 'notifications'")); assertThat(output).contains("Found 1 plugins matching 'notifications'");
assertThat(output, containsString("plugin-notifications")); assertThat(output).contains("plugin-notifications");
assertThat(output, not(containsString("plugin-scripts"))); assertThat(output).doesNotContain("plugin-scripts");
} }
} }
@@ -97,9 +96,9 @@ class PluginSearchCommandTest {
PicocliRunner.call(PluginSearchCommand.class, ctx, args); PicocliRunner.call(PluginSearchCommand.class, ctx, args);
String output = outputStreamCaptor.toString().trim(); String output = outputStreamCaptor.toString().trim();
assertThat(output, containsString("Found 2 plugins")); assertThat(output).contains("Found 2 plugins");
assertThat(output, containsString("plugin-notifications")); assertThat(output).contains("plugin-notifications");
assertThat(output, containsString("plugin-scripts")); assertThat(output).contains("plugin-scripts");
} }
} }
} }

View File

@@ -11,9 +11,7 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
class ReindexCommandTest { class ReindexCommandTest {
@Test @Test
@@ -36,7 +34,7 @@ class ReindexCommandTest {
directory.getPath(), directory.getPath(),
}; };
PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, updateArgs); PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, updateArgs);
assertThat(out.toString(), containsString("3 flow(s)")); assertThat(out.toString()).contains("3 flow(s)");
// then we reindex them // then we reindex them
String[] reindexArgs = { String[] reindexArgs = {
@@ -44,9 +42,9 @@ class ReindexCommandTest {
"flow", "flow",
}; };
Integer call = PicocliRunner.call(ReindexCommand.class, ctx, reindexArgs); Integer call = PicocliRunner.call(ReindexCommand.class, ctx, reindexArgs);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
// in local it reindex 3 flows and in CI 4 for an unknown reason // in local it reindex 3 flows and in CI 4 for an unknown reason
assertThat(out.toString(), containsString("Successfully reindex")); assertThat(out.toString()).contains("Successfully reindex");
} }
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class DatabaseCommandTest { class DatabaseCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class DatabaseCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(DatabaseCommand.class, ctx, args); Integer call = PicocliRunner.call(DatabaseCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra sys database")); assertThat(out.toString()).contains("Usage: kestra sys database");
} }
} }
} }

View File

@@ -8,9 +8,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class StateStoreCommandTest { class StateStoreCommandTest {
@Test @Test
@@ -22,8 +20,8 @@ class StateStoreCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(StateStoreCommand.class, ctx, args); Integer call = PicocliRunner.call(StateStoreCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra sys state-store")); assertThat(out.toString()).contains("Usage: kestra sys state-store");
} }
} }
} }

View File

@@ -25,8 +25,7 @@ import java.net.URI;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
class StateStoreMigrateCommandTest { class StateStoreMigrateCommandTest {
@Test @Test
@@ -54,10 +53,7 @@ class StateStoreMigrateCommandTest {
oldStateStoreUri, oldStateStoreUri,
new ByteArrayInputStream("my-value".getBytes()) new ByteArrayInputStream("my-value".getBytes())
); );
assertThat( assertThat(storage.exists(tenantId, flow.getNamespace(), oldStateStoreUri)).isEqualTo(true);
storage.exists(tenantId, flow.getNamespace(), oldStateStoreUri),
is(true)
);
RunContext runContext = ctx.getBean(RunContextFactory.class).of(flow, Map.of("flow", Map.of( RunContext runContext = ctx.getBean(RunContextFactory.class).of(flow, Map.of("flow", Map.of(
"tenantId", tenantId, "tenantId", tenantId,
@@ -70,13 +66,10 @@ class StateStoreMigrateCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(StateStoreMigrateCommand.class, ctx, args); Integer call = PicocliRunner.call(StateStoreMigrateCommand.class, ctx, args);
assertThat(new String(stateStore.getState(true, "my-state", "sub-name", "my-taskrun-value").readAllBytes()), is("my-value")); assertThat(new String(stateStore.getState(true, "my-state", "sub-name", "my-taskrun-value").readAllBytes())).isEqualTo("my-value");
assertThat( assertThat(storage.exists(tenantId, flow.getNamespace(), oldStateStoreUri)).isEqualTo(false);
storage.exists(tenantId, flow.getNamespace(), oldStateStoreUri),
is(false)
);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
} }
} }
} }

View File

@@ -15,9 +15,7 @@ import java.net.URL;
import java.util.Map; import java.util.Map;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.core.Is.is;
class TemplateExportCommandTest { class TemplateExportCommandTest {
@Test @Test
@@ -42,7 +40,7 @@ class TemplateExportCommandTest {
}; };
PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("3 template(s)")); assertThat(out.toString()).contains("3 template(s)");
// then we export them // then we export them
String[] exportArgs = { String[] exportArgs = {
@@ -56,9 +54,9 @@ class TemplateExportCommandTest {
}; };
PicocliRunner.call(TemplateExportCommand.class, ctx, exportArgs); PicocliRunner.call(TemplateExportCommand.class, ctx, exportArgs);
File file = new File("/tmp/templates.zip"); File file = new File("/tmp/templates.zip");
assertThat(file.exists(), is(true)); assertThat(file.exists()).isEqualTo(true);
ZipFile zipFile = new ZipFile(file); ZipFile zipFile = new ZipFile(file);
assertThat(zipFile.stream().count(), is(3L)); assertThat(zipFile.stream().count()).isEqualTo(3L);
file.delete(); file.delete();
} }

View File

@@ -11,9 +11,7 @@ import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
public class TemplateValidateCommandTest { public class TemplateValidateCommandTest {
@Test @Test
@@ -29,9 +27,9 @@ public class TemplateValidateCommandTest {
}; };
Integer call = PicocliRunner.call(TemplateValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(TemplateValidateCommand.class, ctx, args);
assertThat(call, is(1)); assertThat(call).isEqualTo(1);
assertThat(out.toString(), containsString("Unable to parse template")); assertThat(out.toString()).contains("Unable to parse template");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
@@ -55,9 +53,9 @@ public class TemplateValidateCommandTest {
}; };
Integer call = PicocliRunner.call(TemplateValidateCommand.class, ctx, args); Integer call = PicocliRunner.call(TemplateValidateCommand.class, ctx, args);
assertThat(call, is(1)); assertThat(call).isEqualTo(1);
assertThat(out.toString(), containsString("Unable to parse template")); assertThat(out.toString()).contains("Unable to parse template");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
} }

View File

@@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
class TemplateNamespaceCommandTest { class TemplateNamespaceCommandTest {
@Test @Test
@@ -21,8 +19,8 @@ class TemplateNamespaceCommandTest {
String[] args = {}; String[] args = {};
Integer call = PicocliRunner.call(TemplateNamespaceCommand.class, ctx, args); Integer call = PicocliRunner.call(TemplateNamespaceCommand.class, ctx, args);
assertThat(call, is(0)); assertThat(call).isEqualTo(0);
assertThat(out.toString(), containsString("Usage: kestra template namespace")); assertThat(out.toString()).contains("Usage: kestra template namespace");
} }
} }
} }

View File

@@ -11,8 +11,7 @@ import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.StringContains.containsString;
class TemplateNamespaceUpdateCommandTest { class TemplateNamespaceUpdateCommandTest {
@Test @Test
@@ -37,7 +36,7 @@ class TemplateNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("3 template(s)")); assertThat(out.toString()).contains("3 template(s)");
} }
} }
@@ -64,8 +63,8 @@ class TemplateNamespaceUpdateCommandTest {
Integer call = PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args); Integer call = PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args);
// assertThat(call, is(1)); // assertThat(call, is(1));
assertThat(out.toString(), containsString("Unable to parse templates")); assertThat(out.toString()).contains("Unable to parse templates");
assertThat(out.toString(), containsString("must not be empty")); assertThat(out.toString()).contains("must not be empty");
} }
} }
@@ -93,7 +92,7 @@ class TemplateNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args); PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, args);
assertThat(out.toString(), containsString("3 template(s)")); assertThat(out.toString()).contains("3 template(s)");
String[] newArgs = { String[] newArgs = {
"--server", "--server",
@@ -107,7 +106,7 @@ class TemplateNamespaceUpdateCommandTest {
}; };
PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, newArgs); PicocliRunner.call(TemplateNamespaceUpdateCommand.class, ctx, newArgs);
assertThat(out.toString(), containsString("1 template(s)")); assertThat(out.toString()).contains("1 template(s)");
} }
} }
} }

View File

@@ -10,8 +10,7 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class DeleteConfigurationApplicationListenersTest { class DeleteConfigurationApplicationListenersTest {
@@ -28,7 +27,7 @@ class DeleteConfigurationApplicationListenersTest {
); );
try (ApplicationContext ctx = ApplicationContext.run(mapPropertySource, Environment.CLI, Environment.TEST)) { try (ApplicationContext ctx = ApplicationContext.run(mapPropertySource, Environment.CLI, Environment.TEST)) {
assertThat(tempFile.exists(), is(false)); assertThat(tempFile.exists()).isEqualTo(false);
} }
} }
} }

View File

@@ -19,8 +19,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import static io.kestra.core.utils.Rethrow.throwRunnable; import static io.kestra.core.utils.Rethrow.throwRunnable;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@MicronautTest(environments = {"test", "file-watch"}, transactional = false) @MicronautTest(environments = {"test", "file-watch"}, transactional = false)
class FileChangedEventListenerTest { class FileChangedEventListenerTest {
@@ -77,9 +76,9 @@ class FileChangedEventListenerTest {
Duration.ofSeconds(10) Duration.ofSeconds(10)
); );
Flow myflow = flowRepository.findById(null, "io.kestra.tests.watch", "myflow").orElseThrow(); Flow myflow = flowRepository.findById(null, "io.kestra.tests.watch", "myflow").orElseThrow();
assertThat(myflow.getTasks(), hasSize(1)); assertThat(myflow.getTasks()).hasSize(1);
assertThat(myflow.getTasks().getFirst().getId(), is("hello")); assertThat(myflow.getTasks().getFirst().getId()).isEqualTo("hello");
assertThat(myflow.getTasks().getFirst().getType(), is("io.kestra.plugin.core.log.Log")); assertThat(myflow.getTasks().getFirst().getType()).isEqualTo("io.kestra.plugin.core.log.Log");
// delete the flow // delete the flow
Files.delete(Path.of(FILE_WATCH + "/myflow.yaml")); Files.delete(Path.of(FILE_WATCH + "/myflow.yaml"));
@@ -116,9 +115,9 @@ class FileChangedEventListenerTest {
Duration.ofSeconds(10) Duration.ofSeconds(10)
); );
Flow pluginDefaultFlow = flowRepository.findById(null, "io.kestra.tests.watch", "pluginDefault").orElseThrow(); Flow pluginDefaultFlow = flowRepository.findById(null, "io.kestra.tests.watch", "pluginDefault").orElseThrow();
assertThat(pluginDefaultFlow.getTasks(), hasSize(1)); assertThat(pluginDefaultFlow.getTasks()).hasSize(1);
assertThat(pluginDefaultFlow.getTasks().getFirst().getId(), is("helloWithDefault")); assertThat(pluginDefaultFlow.getTasks().getFirst().getId()).isEqualTo("helloWithDefault");
assertThat(pluginDefaultFlow.getTasks().getFirst().getType(), is("io.kestra.plugin.core.log.Log")); assertThat(pluginDefaultFlow.getTasks().getFirst().getType()).isEqualTo("io.kestra.plugin.core.log.Log");
// delete both files // delete both files
Files.delete(Path.of(FILE_WATCH + "/plugin-default.yaml")); Files.delete(Path.of(FILE_WATCH + "/plugin-default.yaml"));

View File

@@ -8,8 +8,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
class KestraContextTest { class KestraContextTest {
@@ -23,7 +22,7 @@ class KestraContextTest {
context.injectWorkerConfigs(16, null); context.injectWorkerConfigs(16, null);
// Then // Then
assertThat(KestraContext.getContext().getWorkerMaxNumThreads(), is(Optional.of(16))); assertThat(KestraContext.getContext().getWorkerMaxNumThreads()).isEqualTo(Optional.of(16));
} }
@Test @Test
@@ -32,6 +31,6 @@ class KestraContextTest {
context.injectWorkerConfigs(null, "my-key"); context.injectWorkerConfigs(null, "my-key");
// Then // Then
assertThat(KestraContext.getContext().getWorkerGroupKey(), is(Optional.of("my-key"))); assertThat(KestraContext.getContext().getWorkerGroupKey()).isEqualTo(Optional.of("my-key"));
} }
} }

View File

@@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@KestraTest(environments = "maven") @KestraTest(environments = "maven")
class MavenPluginRepositoryConfigTest { class MavenPluginRepositoryConfigTest {
@@ -19,20 +19,16 @@ class MavenPluginRepositoryConfigTest {
@Test @Test
void shouldInjectAllMavenPluginRepositories() { void shouldInjectAllMavenPluginRepositories() {
Assertions.assertEquals(2, repositories.size()); Assertions.assertEquals(2, repositories.size());
assertThat(repositories, Matchers.containsInAnyOrder( assertThat(repositories).containsExactlyInAnyOrder(MavenPluginRepositoryConfig.builder()
MavenPluginRepositoryConfig.builder() .id("central")
.id("central") .url("https://repo.maven.apache.org/maven2/")
.url("https://repo.maven.apache.org/maven2/") .build(), MavenPluginRepositoryConfig.builder()
.build(), .id("secured")
.url("https://registry.test.org/maven")
MavenPluginRepositoryConfig.builder() .basicAuth(new MavenPluginRepositoryConfig.BasicAuth(
.id("secured") "username",
.url("https://registry.test.org/maven") "password"
.basicAuth(new MavenPluginRepositoryConfig.BasicAuth( ))
"username", .build());
"password"
))
.build()
));
} }
} }

View File

@@ -20,8 +20,7 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import static io.kestra.core.utils.Rethrow.throwConsumer; import static io.kestra.core.utils.Rethrow.throwConsumer;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
class ClassPluginDocumentationTest { class ClassPluginDocumentationTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -35,60 +34,60 @@ class ClassPluginDocumentationTest {
PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader()); PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader());
List<RegisteredPlugin> scan = pluginScanner.scan(plugins); List<RegisteredPlugin> scan = pluginScanner.scan(plugins);
assertThat(scan.size(), is(1)); assertThat(scan.size()).isEqualTo(1);
assertThat(scan.getFirst().getTasks().size(), is(1)); assertThat(scan.getFirst().getTasks().size()).isEqualTo(1);
PluginClassAndMetadata<Task> metadata = PluginClassAndMetadata.create(scan.getFirst(), scan.getFirst().getTasks().getFirst(), Task.class, null); PluginClassAndMetadata<Task> metadata = PluginClassAndMetadata.create(scan.getFirst(), scan.getFirst().getTasks().getFirst(), Task.class, null);
ClassPluginDocumentation<? extends Task> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false); ClassPluginDocumentation<? extends Task> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false);
assertThat(doc.getDocExamples().size(), is(2)); assertThat(doc.getDocExamples().size()).isEqualTo(2);
assertThat(doc.getIcon(), is(notNullValue())); assertThat(doc.getIcon()).isNotNull();
assertThat(doc.getInputs().size(), is(5)); assertThat(doc.getInputs().size()).isEqualTo(5);
assertThat(doc.getDocLicense(), is("EE")); assertThat(doc.getDocLicense()).isEqualTo("EE");
// simple // simple
assertThat(((Map<String, String>) doc.getInputs().get("format")).get("type"), is("string")); assertThat(((Map<String, String>) doc.getInputs().get("format")).get("type")).isEqualTo("string");
assertThat(((Map<String, String>) doc.getInputs().get("format")).get("default"), is("{}")); assertThat(((Map<String, String>) doc.getInputs().get("format")).get("default")).isEqualTo("{}");
assertThat(((Map<String, String>) doc.getInputs().get("format")).get("pattern"), is(".*")); assertThat(((Map<String, String>) doc.getInputs().get("format")).get("pattern")).isEqualTo(".*");
assertThat(((Map<String, String>) doc.getInputs().get("format")).get("description"), containsString("of this input")); assertThat(((Map<String, String>) doc.getInputs().get("format")).get("description")).contains("of this input");
// definitions // definitions
assertThat(doc.getDefs().size(), is(5)); assertThat(doc.getDefs().size()).isEqualTo(5);
// enum // enum
Map<String, Object> enumProperties = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput")).get("properties")).get("childEnum"); Map<String, Object> enumProperties = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput")).get("properties")).get("childEnum");
assertThat(((List<String>) enumProperties.get("enum")).size(), is(2)); assertThat(((List<String>) enumProperties.get("enum")).size()).isEqualTo(2);
assertThat(((List<String>) enumProperties.get("enum")), containsInAnyOrder("VALUE_1", "VALUE_2")); assertThat(((List<String>) enumProperties.get("enum"))).containsExactlyInAnyOrder("VALUE_1", "VALUE_2");
Map<String, Object> childInput = (Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput")).get("properties"); Map<String, Object> childInput = (Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput")).get("properties");
// array // array
Map<String, Object> childInputList = (Map<String, Object>) childInput.get("list"); Map<String, Object> childInputList = (Map<String, Object>) childInput.get("list");
assertThat((String) (childInputList).get("type"), is("array")); assertThat((String) (childInputList).get("type")).isEqualTo("array");
assertThat((String) (childInputList).get("title"), is("List of string")); assertThat((String) (childInputList).get("title")).isEqualTo("List of string");
assertThat((Integer) (childInputList).get("minItems"), is(1)); assertThat((Integer) (childInputList).get("minItems")).isEqualTo(1);
assertThat(((Map<String, String>) (childInputList).get("items")).get("type"), is("string")); assertThat(((Map<String, String>) (childInputList).get("items")).get("type")).isEqualTo("string");
// map // map
Map<String, Object> childInputMap = (Map<String, Object>) childInput.get("map"); Map<String, Object> childInputMap = (Map<String, Object>) childInput.get("map");
assertThat((String) (childInputMap).get("type"), is("object")); assertThat((String) (childInputMap).get("type")).isEqualTo("object");
assertThat((Boolean) (childInputMap).get("$dynamic"), is(true)); assertThat((Boolean) (childInputMap).get("$dynamic")).isEqualTo(true);
assertThat(((Map<String, String>) (childInputMap).get("additionalProperties")).get("type"), is("number")); assertThat(((Map<String, String>) (childInputMap).get("additionalProperties")).get("type")).isEqualTo("number");
// output // output
Map<String, Object> childOutput = (Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.AbstractTask-OutputChild")).get("properties"); Map<String, Object> childOutput = (Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.AbstractTask-OutputChild")).get("properties");
assertThat(((Map<String, String>) childOutput.get("value")).get("type"), is("string")); assertThat(((Map<String, String>) childOutput.get("value")).get("type")).isEqualTo("string");
assertThat(((Map<String, Object>) childOutput.get("outputChildMap")).get("type"), is("object")); assertThat(((Map<String, Object>) childOutput.get("outputChildMap")).get("type")).isEqualTo("object");
assertThat(((Map<String, String>)((Map<String, Object>) childOutput.get("outputChildMap")).get("additionalProperties")).get("$ref"), containsString("OutputMap")); assertThat(((Map<String, String>) ((Map<String, Object>) childOutput.get("outputChildMap")).get("additionalProperties")).get("$ref")).contains("OutputMap");
// required // required
Map<String, Object> propertiesChild = (Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput"); Map<String, Object> propertiesChild = (Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput");
assertThat(((List<String>) propertiesChild.get("required")).size(), is(3)); assertThat(((List<String>) propertiesChild.get("required")).size()).isEqualTo(3);
// output ref // output ref
Map<String, Object> outputMap = ((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.AbstractTask-OutputMap")).get("properties")); Map<String, Object> outputMap = ((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.AbstractTask-OutputMap")).get("properties"));
assertThat(outputMap.size(), is(2)); assertThat(outputMap.size()).isEqualTo(2);
assertThat(((Map<String, Object>) outputMap.get("code")).get("type"), is("integer")); assertThat(((Map<String, Object>) outputMap.get("code")).get("type")).isEqualTo("integer");
})); }));
} }
@@ -104,11 +103,11 @@ class ClassPluginDocumentationTest {
PluginClassAndMetadata<AbstractTrigger> metadata = PluginClassAndMetadata.create(scan, Schedule.class, AbstractTrigger.class, null); PluginClassAndMetadata<AbstractTrigger> metadata = PluginClassAndMetadata.create(scan, Schedule.class, AbstractTrigger.class, null);
ClassPluginDocumentation<? extends AbstractTrigger> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, true); ClassPluginDocumentation<? extends AbstractTrigger> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, true);
assertThat(doc.getDefs().size(), is(1)); assertThat(doc.getDefs().size()).isEqualTo(1);
assertThat(doc.getDocLicense(), nullValue()); assertThat(doc.getDocLicense()).isNull();
assertThat(((Map<String, Object>) doc.getDefs().get("io.kestra.core.models.tasks.WorkerGroup")).get("type"), is("object")); assertThat(((Map<String, Object>) doc.getDefs().get("io.kestra.core.models.tasks.WorkerGroup")).get("type")).isEqualTo("object");
assertThat(((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.core.models.tasks.WorkerGroup")).get("properties")).size(), is(2)); assertThat(((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.core.models.tasks.WorkerGroup")).get("properties")).size()).isEqualTo(2);
})); }));
} }
@@ -123,10 +122,10 @@ class ClassPluginDocumentationTest {
PluginClassAndMetadata<? extends TaskRunner<?>> metadata = PluginClassAndMetadata.create(scan, Process.class, Process.class, null); PluginClassAndMetadata<? extends TaskRunner<?>> metadata = PluginClassAndMetadata.create(scan, Process.class, Process.class, null);
ClassPluginDocumentation<? extends TaskRunner<?>> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false); ClassPluginDocumentation<? extends TaskRunner<?>> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false);
assertThat(((Map<?, ?>) doc.getPropertiesSchema().get("properties")).get("version"), notNullValue()); assertThat(((Map<?, ?>) doc.getPropertiesSchema().get("properties")).get("version")).isNotNull();
assertThat(doc.getCls(), is("io.kestra.plugin.core.runner.Process")); assertThat(doc.getCls()).isEqualTo("io.kestra.plugin.core.runner.Process");
assertThat(doc.getPropertiesSchema().get("title"), is("Task runner that executes a task as a subprocess on the Kestra host.")); assertThat(doc.getPropertiesSchema().get("title")).isEqualTo("Task runner that executes a task as a subprocess on the Kestra host.");
assertThat(doc.getDefs(), anEmptyMap()); assertThat(doc.getDefs()).isEmpty();
})); }));
} }
@@ -142,28 +141,28 @@ class ClassPluginDocumentationTest {
PluginClassAndMetadata<DynamicPropertyExampleTask> metadata = PluginClassAndMetadata.create(scan, DynamicPropertyExampleTask.class, DynamicPropertyExampleTask.class, null); PluginClassAndMetadata<DynamicPropertyExampleTask> metadata = PluginClassAndMetadata.create(scan, DynamicPropertyExampleTask.class, DynamicPropertyExampleTask.class, null);
ClassPluginDocumentation<? extends DynamicPropertyExampleTask> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, true); ClassPluginDocumentation<? extends DynamicPropertyExampleTask> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, true);
assertThat(doc.getCls(), is("io.kestra.core.models.property.DynamicPropertyExampleTask")); assertThat(doc.getCls()).isEqualTo("io.kestra.core.models.property.DynamicPropertyExampleTask");
assertThat(doc.getDefs(), aMapWithSize(6)); assertThat(doc.getDefs()).hasSize(6);
Map<String, Object> properties = (Map<String, Object>) doc.getPropertiesSchema().get("properties"); Map<String, Object> properties = (Map<String, Object>) doc.getPropertiesSchema().get("properties");
assertThat(properties, aMapWithSize(21)); assertThat(properties).hasSize(21);
Map<String, Object> number = (Map<String, Object>) properties.get("number"); Map<String, Object> number = (Map<String, Object>) properties.get("number");
assertThat(number.get("anyOf"), notNullValue()); assertThat(number.get("anyOf")).isNotNull();
List<Map<String, Object>> anyOf = (List<Map<String, Object>>) number.get("anyOf"); List<Map<String, Object>> anyOf = (List<Map<String, Object>>) number.get("anyOf");
assertThat(anyOf, hasSize(2)); assertThat(anyOf).hasSize(2);
assertThat(anyOf.getFirst().get("type"), is("integer")); assertThat(anyOf.getFirst().get("type")).isEqualTo("integer");
assertThat(anyOf.getFirst().get("$dynamic"), is(true)); assertThat(anyOf.getFirst().get("$dynamic")).isEqualTo(true);
assertThat(anyOf.get(1).get("type"), is("string")); assertThat(anyOf.get(1).get("type")).isEqualTo("string");
// assertThat(anyOf.get(1).get("pattern"), is(".*{{.*}}.*")); // assertThat(anyOf.get(1).get("pattern"), is(".*{{.*}}.*"));
Map<String, Object> withDefault = (Map<String, Object>) properties.get("withDefault"); Map<String, Object> withDefault = (Map<String, Object>) properties.get("withDefault");
assertThat(withDefault.get("type"), is("string")); assertThat(withDefault.get("type")).isEqualTo("string");
assertThat(withDefault.get("default"), is("Default Value")); assertThat(withDefault.get("default")).isEqualTo("Default Value");
assertThat(withDefault.get("$dynamic"), is(true)); assertThat(withDefault.get("$dynamic")).isEqualTo(true);
Map<String, Object> internalStorageURI = (Map<String, Object>) properties.get("uri"); Map<String, Object> internalStorageURI = (Map<String, Object>) properties.get("uri");
assertThat(internalStorageURI.get("type"), is("string")); assertThat(internalStorageURI.get("type")).isEqualTo("string");
assertThat(internalStorageURI.get("$internalStorageURI"), is(true)); assertThat(internalStorageURI.get("$internalStorageURI")).isEqualTo(true);
})); }));
} }
} }

View File

@@ -22,8 +22,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
class DocumentationGeneratorTest { class DocumentationGeneratorTest {
@@ -40,17 +39,17 @@ class DocumentationGeneratorTest {
PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader()); PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader());
List<RegisteredPlugin> scan = pluginScanner.scan(plugins); List<RegisteredPlugin> scan = pluginScanner.scan(plugins);
assertThat(scan.size(), is(1)); assertThat(scan.size()).isEqualTo(1);
PluginClassAndMetadata<Task> metadata = PluginClassAndMetadata.create(scan.getFirst(), scan.getFirst().getTasks().getFirst(), Task.class, null); PluginClassAndMetadata<Task> metadata = PluginClassAndMetadata.create(scan.getFirst(), scan.getFirst().getTasks().getFirst(), Task.class, null);
ClassPluginDocumentation<? extends Task> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false); ClassPluginDocumentation<? extends Task> doc = ClassPluginDocumentation.of(jsonSchemaGenerator, metadata, false);
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("ExampleTask")); assertThat(render).contains("ExampleTask");
assertThat(render, containsString("description: \"Short description for this task\"")); assertThat(render).contains("description: \"Short description for this task\"");
assertThat(render, containsString("`VALUE_1`")); assertThat(render).contains("`VALUE_1`");
assertThat(render, containsString("`VALUE_2`")); assertThat(render).contains("`VALUE_2`");
assertThat(render, containsString("This plugin is exclusively available on the Cloud and Enterprise editions of Kestra.")); assertThat(render).contains("This plugin is exclusively available on the Cloud and Enterprise editions of Kestra.");
} }
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@@ -65,10 +64,10 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("Dag")); assertThat(render).contains("Dag");
assertThat(render, containsString("**Required:** ✔️")); assertThat(render).contains("**Required:** ✔️");
assertThat(render, containsString("`concurrent`")); assertThat(render).contains("`concurrent`");
assertThat(render, not(containsString("requires an Enterprise Edition"))); assertThat(render).doesNotContain("requires an Enterprise Edition");
int propertiesIndex = render.indexOf("Properties"); int propertiesIndex = render.indexOf("Properties");
int definitionsIndex = render.indexOf("Definitions"); int definitionsIndex = render.indexOf("Definitions");
@@ -86,7 +85,7 @@ class DocumentationGeneratorTest {
int lastRequiredPropIndex = propertiesDoc.lastIndexOf("* **Required:** ✔️"); int lastRequiredPropIndex = propertiesDoc.lastIndexOf("* **Required:** ✔️");
int firstOptionalPropIndex = propertiesDoc.indexOf("* **Required:** ❌"); int firstOptionalPropIndex = propertiesDoc.indexOf("* **Required:** ❌");
if (lastRequiredPropIndex != -1 && firstOptionalPropIndex != -1) { if (lastRequiredPropIndex != -1 && firstOptionalPropIndex != -1) {
assertThat(lastRequiredPropIndex, lessThanOrEqualTo(firstOptionalPropIndex)); assertThat(lastRequiredPropIndex).isLessThanOrEqualTo(firstOptionalPropIndex);
} }
} }
@@ -102,11 +101,11 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("Return a value for debugging purposes.")); assertThat(render).contains("Return a value for debugging purposes.");
assertThat(render, containsString("is intended for troubleshooting")); assertThat(render).contains("is intended for troubleshooting");
assertThat(render, containsString("## Metrics")); assertThat(render).contains("## Metrics");
assertThat(render, containsString("### `length`\n" + "* **Type:** ==counter== ")); assertThat(render).contains("### `length`\n" + "* **Type:** ==counter== ");
assertThat(render, containsString("### `duration`\n" + "* **Type:** ==timer== ")); assertThat(render).contains("### `duration`\n" + "* **Type:** ==timer== ");
} }
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@@ -121,7 +120,7 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("* **Default:** `false`")); assertThat(render).contains("* **Default:** `false`");
} }
@SuppressWarnings({"unchecked", "deprecation"}) @SuppressWarnings({"unchecked", "deprecation"})
@@ -136,8 +135,8 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("Echo")); assertThat(render).contains("Echo");
assertThat(render, containsString("This feature is deprecated and will be removed in the future")); assertThat(render).contains("This feature is deprecated and will be removed in the future");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -152,8 +151,8 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("Set")); assertThat(render).contains("Set");
assertThat(render, containsString("::alert{type=\"warning\"}\n")); assertThat(render).contains("::alert{type=\"warning\"}\n");
} }
@Test @Test
@@ -163,8 +162,8 @@ class DocumentationGeneratorTest {
List<Document> docs = documentationGenerator.generate(core); List<Document> docs = documentationGenerator.generate(core);
Document doc = docs.getFirst(); Document doc = docs.getFirst();
assertThat(doc.getIcon(), is(notNullValue())); assertThat(doc.getIcon()).isNotNull();
assertThat(doc.getBody(), containsString("## <img width=\"25\" src=\"data:image/svg+xml;base64,")); assertThat(doc.getBody()).contains("## <img width=\"25\" src=\"data:image/svg+xml;base64,");
} }
@Test @Test
@@ -176,7 +175,7 @@ class DocumentationGeneratorTest {
List<Document> docs = documentationGenerator.generate(list.stream().filter(r -> r.license() != null).findFirst().orElseThrow()); List<Document> docs = documentationGenerator.generate(list.stream().filter(r -> r.license() != null).findFirst().orElseThrow());
Document doc = docs.getFirst(); Document doc = docs.getFirst();
assertThat(doc.getBody(), containsString("This plugin is exclusively available on the Cloud and Enterprise editions of Kestra.")); assertThat(doc.getBody()).contains("This plugin is exclusively available on the Cloud and Enterprise editions of Kestra.");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -191,7 +190,7 @@ class DocumentationGeneratorTest {
String render = DocumentationGenerator.render(doc); String render = DocumentationGenerator.render(doc);
assertThat(render, containsString("title: Process")); assertThat(render).contains("title: Process");
assertThat(render, containsString("Task runner that executes a task as a subprocess on the Kestra host.")); assertThat(render).contains("Task runner that executes a task as a subprocess on the Kestra host.");
} }
} }

View File

@@ -4,9 +4,7 @@ import org.junit.jupiter.api.Test;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class EncryptionServiceTest { public class EncryptionServiceTest {
private static final String KEY = "I6EGNzRESu3X3pKZidrqCGOHQFUFC0yK"; private static final String KEY = "I6EGNzRESu3X3pKZidrqCGOHQFUFC0yK";
@@ -16,7 +14,7 @@ public class EncryptionServiceTest {
String text = "Hello World!"; String text = "Hello World!";
String encrypted = EncryptionService.encrypt(KEY, text); String encrypted = EncryptionService.encrypt(KEY, text);
String decrypted = EncryptionService.decrypt(KEY, encrypted); String decrypted = EncryptionService.decrypt(KEY, encrypted);
assertThat(decrypted, is(text)); assertThat(decrypted).isEqualTo(text);
} }
@Test @Test
@@ -24,16 +22,16 @@ public class EncryptionServiceTest {
byte[] text = "Hello World!".getBytes(); byte[] text = "Hello World!".getBytes();
byte[] encrypted = EncryptionService.encrypt(KEY, text); byte[] encrypted = EncryptionService.encrypt(KEY, text);
byte[] decrypted = EncryptionService.decrypt(KEY, encrypted); byte[] decrypted = EncryptionService.decrypt(KEY, encrypted);
assertThat(new String(decrypted), is("Hello World!")); assertThat(new String(decrypted)).isEqualTo("Hello World!");
} }
@Test @Test
void avoidNpeForEmptyOrNullText() throws GeneralSecurityException { void avoidNpeForEmptyOrNullText() throws GeneralSecurityException {
assertThat(EncryptionService.encrypt(KEY, (String) null), nullValue()); assertThat(EncryptionService.encrypt(KEY, (String) null)).isNull();
assertThat(EncryptionService.decrypt(KEY, (String) null), nullValue()); assertThat(EncryptionService.decrypt(KEY, (String) null)).isNull();
assertThat(EncryptionService.encrypt(KEY, (byte[]) null), nullValue()); assertThat(EncryptionService.encrypt(KEY, (byte[]) null)).isNull();
assertThat(EncryptionService.decrypt(KEY, (byte[]) null), nullValue()); assertThat(EncryptionService.decrypt(KEY, (byte[]) null)).isNull();
assertThat(EncryptionService.encrypt(KEY, ""), is("")); assertThat(EncryptionService.encrypt(KEY, "")).isEqualTo("");
assertThat(EncryptionService.decrypt(KEY, ""), is("")); assertThat(EncryptionService.decrypt(KEY, "")).isEqualTo("");
} }
} }

View File

@@ -15,8 +15,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -51,7 +50,7 @@ class BasicAuthEndpointsFilterTest {
void withPasswordOk() { void withPasswordOk() {
test(true, (client, httpRequest) -> { test(true, (client, httpRequest) -> {
HttpResponse<String> response = client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar")); HttpResponse<String> response = client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar"));
assertThat(response.getStatus(), is(HttpStatus.OK)); assertThat(response.getStatus().getCode()).isEqualTo(HttpStatus.OK.getCode());
}); });
} }
@@ -62,7 +61,7 @@ class BasicAuthEndpointsFilterTest {
client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar2")); client.toBlocking().exchange(httpRequest.basicAuth("foo", "bar2"));
}); });
assertThat(e.getStatus(), is(HttpStatus.UNAUTHORIZED)); assertThat(e.getStatus().getCode()).isEqualTo(HttpStatus.UNAUTHORIZED.getCode());
}); });
test(true, (client, httpRequest) -> { test(true, (client, httpRequest) -> {
@@ -70,7 +69,7 @@ class BasicAuthEndpointsFilterTest {
client.toBlocking().exchange(httpRequest); client.toBlocking().exchange(httpRequest);
}); });
assertThat(e.getStatus(), is(HttpStatus.UNAUTHORIZED)); assertThat(e.getStatus().getCode()).isEqualTo(HttpStatus.UNAUTHORIZED.getCode());
}); });
} }
@@ -78,7 +77,7 @@ class BasicAuthEndpointsFilterTest {
void withoutPasswordOk() { void withoutPasswordOk() {
test(false, (client, httpRequest) -> { test(false, (client, httpRequest) -> {
HttpResponse<String> response = client.toBlocking().exchange(httpRequest); HttpResponse<String> response = client.toBlocking().exchange(httpRequest);
assertThat(response.getStatus(), is(HttpStatus.OK)); assertThat(response.getStatus().getCode()).isEqualTo(HttpStatus.OK.getCode());
}); });
} }
} }

View File

@@ -60,8 +60,8 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.apache.commons.lang3.ArrayUtils.toPrimitive;
import static org.hamcrest.Matchers.*; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@KestraTest @KestraTest
@@ -133,14 +133,14 @@ class HttpClientTest {
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), is("pong")); assertThat(response.getBody()).isEqualTo("pong");
List<LogEntry> logEntries = TestsUtils.awaitLogs(logs, 6); List<LogEntry> logEntries = TestsUtils.awaitLogs(logs, 6);
assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().startsWith("request")).count(), is(3L)); assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().startsWith("request")).count()).isEqualTo(3L);
assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().contains("X-Unit: Test")).count(), is(1L)); assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().contains("X-Unit: Test")).count()).isEqualTo(1L);
assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().startsWith("response")).count(), is(3L)); assertThat(logEntries.stream().filter(logEntry -> logEntry.getMessage().startsWith("response")).count()).isEqualTo(3L);
} }
} }
@@ -152,8 +152,8 @@ class HttpClientTest {
Byte[].class Byte[].class
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), is("pong".getBytes(StandardCharsets.UTF_8))); assertThat(toPrimitive(response.getBody())).isEqualTo("pong".getBytes(StandardCharsets.UTF_8));
} }
} }
@@ -165,8 +165,8 @@ class HttpClientTest {
String.class String.class
); );
assertThat(response.getStatus().getCode(), is(204)); assertThat(response.getStatus().getCode()).isEqualTo(204);
assertThat(response.getBody(), is(nullValue())); assertThat(response.getBody()).isNull();
} }
} }
@@ -177,9 +177,9 @@ class HttpClientTest {
HttpRequest.of(URI.create(embeddedServerUri + "/http/json")) HttpRequest.of(URI.create(embeddedServerUri + "/http/json"))
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody().get("ping"), is("pong")); assertThat(response.getBody().get("ping")).isEqualTo("pong");
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -190,9 +190,9 @@ class HttpClientTest {
HttpRequest.of(URI.create(embeddedServerUri + "/http/json?array=true")) HttpRequest.of(URI.create(embeddedServerUri + "/http/json?array=true"))
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), containsInAnyOrder(1, 2, 3)); assertThat(response.getBody()).containsExactlyInAnyOrder(1, 2, 3);
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -204,9 +204,9 @@ class HttpClientTest {
String.class String.class
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), is("{\"ping\":\"pong\"}")); assertThat(response.getBody()).isEqualTo("{\"ping\":\"pong\"}");
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -237,9 +237,9 @@ class HttpClientTest {
HttpRequest.of(URI.create(embeddedServerUri + "/http/json-post"), "POST", requestBody) HttpRequest.of(URI.create(embeddedServerUri + "/http/json-post"), "POST", requestBody)
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody().get("ping"), is(UUID)); assertThat(response.getBody().get("ping")).isEqualTo(UUID);
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -256,9 +256,9 @@ class HttpClientTest {
CustomObject.class CustomObject.class
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody().id, is(test.id)); assertThat(response.getBody().id).isEqualTo(test.id);
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -281,13 +281,13 @@ class HttpClientTest {
HttpRequest.of(URI.create(embeddedServerUri + "/http/multipart"), "POST", HttpRequest.MultipartRequestBody.builder().content(multipart).build()) HttpRequest.of(URI.create(embeddedServerUri + "/http/multipart"), "POST", HttpRequest.MultipartRequestBody.builder().content(multipart).build())
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody().get("ping"), is("pong")); assertThat(response.getBody().get("ping")).isEqualTo("pong");
assertThat(response.getBody().get("int"), is("1")); assertThat(response.getBody().get("int")).isEqualTo("1");
assertThat((String) response.getBody().get("file"), containsString("logback")); assertThat((String) response.getBody().get("file")).contains("logback");
// @FIXME: Request seems to be correct, but not returned by micronaut // @FIXME: Request seems to be correct, but not returned by micronaut
// assertThat((String) response.getBody().get("inputStream"), containsString("logback")); // assertThat((String) response.getBody().get("inputStream"), containsString("logback"));
assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow(), is(MediaType.APPLICATION_JSON)); assertThat(response.getHeaders().firstValue(HttpHeaders.CONTENT_TYPE).orElseThrow()).isEqualTo(MediaType.APPLICATION_JSON);
} }
} }
@@ -300,8 +300,8 @@ class HttpClientTest {
client.request(HttpRequest.of(uri)); client.request(HttpRequest.of(uri));
}); });
assertThat(e.getRequest().getUri(), is(uri)); assertThat(e.getRequest().getUri()).isEqualTo(uri);
assertThat(e.getMessage(), containsString("Connection refused")); assertThat(e.getMessage()).contains("Connection refused");
} }
} }
@@ -310,7 +310,7 @@ class HttpClientTest {
try (HttpClient client = client()) { try (HttpClient client = client()) {
HttpResponse<Map<String, String>> response = client.request(HttpRequest.of(URI.create(embeddedServerUri + "/http/error?status=305"))); HttpResponse<Map<String, String>> response = client.request(HttpRequest.of(URI.create(embeddedServerUri + "/http/error?status=305")));
assertThat(response.getStatus().getCode(), is(305)); assertThat(response.getStatus().getCode()).isEqualTo(305);
} }
} }
@@ -323,9 +323,9 @@ class HttpClientTest {
client.request(HttpRequest.of(uri)); client.request(HttpRequest.of(uri));
}); });
assertThat(Objects.requireNonNull(e.getResponse()).getStatus().getCode(), is(400)); assertThat(Objects.requireNonNull(e.getResponse()).getStatus().getCode()).isEqualTo(400);
assertThat(e.getMessage(), containsString("Required QueryValue [status]")); assertThat(e.getMessage()).contains("Required QueryValue [status]");
assertThat(new String((byte[]) e.getResponse().getBody()), containsString("Required QueryValue [status]")); assertThat(new String((byte[]) e.getResponse().getBody())).contains("Required QueryValue [status]");
} }
} }
@@ -338,7 +338,7 @@ class HttpClientTest {
client.request(HttpRequest.of(uri)); client.request(HttpRequest.of(uri));
}); });
assertThat(Objects.requireNonNull(e.getResponse()).getStatus().getCode(), is(404)); assertThat(Objects.requireNonNull(e.getResponse()).getStatus().getCode()).isEqualTo(404);
} }
} }
@@ -347,7 +347,7 @@ class HttpClientTest {
try (HttpClient client = client(b -> b.configuration(HttpConfiguration.builder().allowFailed(Property.of(true)).build()))) { try (HttpClient client = client(b -> b.configuration(HttpConfiguration.builder().allowFailed(Property.of(true)).build()))) {
HttpResponse<Map<String, String>> response = client.request(HttpRequest.of(URI.create(embeddedServerUri + "/http/error?status=404"))); HttpResponse<Map<String, String>> response = client.request(HttpRequest.of(URI.create(embeddedServerUri + "/http/error?status=404")));
assertThat(response.getStatus().getCode(), is(404)); assertThat(response.getStatus().getCode()).isEqualTo(404);
} }
} }
@@ -358,7 +358,7 @@ class HttpClientTest {
HttpResponse<Map<String, String>> response = client.request(HttpRequest.builder().uri(uri).method("POST").body(HttpRequest.StringRequestBody.builder().content("OK").build()).build()); HttpResponse<Map<String, String>> response = client.request(HttpRequest.builder().uri(uri).method("POST").body(HttpRequest.StringRequestBody.builder().content("OK").build()).build());
assertThat(response.getStatus().getCode(), is(404)); assertThat(response.getStatus().getCode()).isEqualTo(404);
} }
} }
@@ -372,8 +372,8 @@ class HttpClientTest {
String.class String.class
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), is("application/vnd.campaignsexport.v1+json")); assertThat(response.getBody()).isEqualTo("application/vnd.campaignsexport.v1+json");
} }
} }
@@ -395,8 +395,8 @@ class HttpClientTest {
String.class String.class
); );
assertThat(response.getStatus().getCode(), is(200)); assertThat(response.getStatus().getCode()).isEqualTo(200);
assertThat(response.getBody(), containsString("<html")); assertThat(response.getBody()).contains("<html");
} }
} }

View File

@@ -9,8 +9,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class ExecutionTest { class ExecutionTest {
private static final TaskRun.TaskRunBuilder TASK_RUN = TaskRun.builder() private static final TaskRun.TaskRunBuilder TASK_RUN = TaskRun.builder()
@@ -30,7 +29,7 @@ class ExecutionTest {
.withState(State.Type.RUNNING) .withState(State.Type.RUNNING)
)) ))
.build() .build()
), is(true)); )).isEqualTo(true);
} }
@Test @Test
@@ -45,7 +44,7 @@ class ExecutionTest {
assertThat(execution.hasTaskRunJoinable(TASK_RUN assertThat(execution.hasTaskRunJoinable(TASK_RUN
.state(new State()) .state(new State())
.build() .build()
), is(false)); )).isEqualTo(false);
} }
@Test @Test
@@ -62,7 +61,7 @@ class ExecutionTest {
assertThat(execution.hasTaskRunJoinable(TASK_RUN assertThat(execution.hasTaskRunJoinable(TASK_RUN
.state(new State(State.Type.RUNNING, new State())) .state(new State(State.Type.RUNNING, new State()))
.build() .build()
), is(false)); )).isEqualTo(false);
} }
@Test @Test
@@ -82,7 +81,7 @@ class ExecutionTest {
.withState(State.Type.RUNNING) .withState(State.Type.RUNNING)
)) ))
.build() .build()
), is(false)); )).isEqualTo(false);
} }
@Test @Test
@@ -103,7 +102,7 @@ class ExecutionTest {
.withState(State.Type.SUCCESS) .withState(State.Type.SUCCESS)
)) ))
.build() .build()
), is(true)); )).isEqualTo(true);
} }
@Test @Test
@@ -126,7 +125,7 @@ class ExecutionTest {
.withState(State.Type.RUNNING) .withState(State.Type.RUNNING)
)) ))
.build() .build()
), is(true)); )).isEqualTo(true);
} }
@Test @Test
@@ -135,21 +134,21 @@ class ExecutionTest {
.id(IdUtils.create()) .id(IdUtils.create())
.state(new State()) .state(new State())
.build(); .build();
assertThat(execution.getOriginalId(), is(execution.getId())); assertThat(execution.getOriginalId()).isEqualTo(execution.getId());
Execution restart1 = execution.childExecution( Execution restart1 = execution.childExecution(
IdUtils.create(), IdUtils.create(),
execution.getTaskRunList(), execution.getTaskRunList(),
execution.withState(State.Type.RESTARTED).getState() execution.withState(State.Type.RESTARTED).getState()
); );
assertThat(restart1.getOriginalId(), is(execution.getId())); assertThat(restart1.getOriginalId()).isEqualTo(execution.getId());
Execution restart2 = restart1.childExecution( Execution restart2 = restart1.childExecution(
IdUtils.create(), IdUtils.create(),
restart1.getTaskRunList(), restart1.getTaskRunList(),
restart1.withState(State.Type.PAUSED).getState() restart1.withState(State.Type.PAUSED).getState()
); );
assertThat(restart2.getOriginalId(), is(execution.getId())); assertThat(restart2.getOriginalId()).isEqualTo(execution.getId());
} }
@Test @Test
@@ -158,7 +157,7 @@ class ExecutionTest {
.labels(List.of(new Label("test", "test-value"))) .labels(List.of(new Label("test", "test-value")))
.build(); .build();
assertThat(execution.getLabels().size(), is(1)); assertThat(execution.getLabels().size()).isEqualTo(1);
assertThat(execution.getLabels().getFirst(), is(new Label("test", "test-value"))); assertThat(execution.getLabels().getFirst()).isEqualTo(new Label("test", "test-value"));
} }
} }

View File

@@ -1,7 +1,6 @@
package io.kestra.core.models.executions; package io.kestra.core.models.executions;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import java.util.Map; import java.util.Map;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -23,16 +22,16 @@ public class LogEntryTest {
.message("message") .message("message")
.build(); .build();
Map<String, Object> logMap = logEntry.toLogMap(); Map<String, Object> logMap = logEntry.toLogMap();
assertThat(logMap.get("tenantId"), is("tenantId")); assertThat(logMap.get("tenantId")).isEqualTo("tenantId");
assertThat(logMap.get("namespace"), is("namespace")); assertThat(logMap.get("namespace")).isEqualTo("namespace");
assertThat(logMap.get("flowId"), is("flowId")); assertThat(logMap.get("flowId")).isEqualTo("flowId");
assertThat(logMap.get("taskId"), is("taskId")); assertThat(logMap.get("taskId")).isEqualTo("taskId");
assertThat(logMap.get("executionId"), is("executionId")); assertThat(logMap.get("executionId")).isEqualTo("executionId");
assertThat(logMap.get("taskRunId"), is("taskRunId")); assertThat(logMap.get("taskRunId")).isEqualTo("taskRunId");
assertThat(logMap.get("attemptNumber"), is(1)); assertThat(logMap.get("attemptNumber")).isEqualTo(1);
assertThat(logMap.get("triggerId"), is("triggerId")); assertThat(logMap.get("triggerId")).isEqualTo("triggerId");
assertThat(logMap.get("thread"), is("thread")); assertThat(logMap.get("thread")).isEqualTo("thread");
assertThat(logMap.get("message"), is("message")); assertThat(logMap.get("message")).isEqualTo("message");
} }
} }

View File

@@ -5,9 +5,7 @@ import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
class TaskRunTest { class TaskRunTest {
@Test @Test
@@ -17,9 +15,9 @@ class TaskRunTest {
.build() .build()
.onRunningResend(); .onRunningResend();
assertThat(taskRun.getAttempts().size(), is(1)); assertThat(taskRun.getAttempts().size()).isEqualTo(1);
assertThat(taskRun.getAttempts().getFirst().getState().getHistories().getFirst(), is(taskRun.getState().getHistories().getFirst())); assertThat(taskRun.getAttempts().getFirst().getState().getHistories().getFirst()).isEqualTo(taskRun.getState().getHistories().getFirst());
assertThat(taskRun.getAttempts().getFirst().getState().getCurrent(), is(State.Type.KILLED)); assertThat(taskRun.getAttempts().getFirst().getState().getCurrent()).isEqualTo(State.Type.KILLED);
} }
@Test @Test
@@ -33,9 +31,9 @@ class TaskRunTest {
.build() .build()
.onRunningResend(); .onRunningResend();
assertThat(taskRun.getAttempts().size(), is(1)); assertThat(taskRun.getAttempts().size()).isEqualTo(1);
assertThat(taskRun.getAttempts().getFirst().getState().getHistories().getFirst(), is(not(taskRun.getState().getHistories().getFirst()))); assertThat(taskRun.getAttempts().getFirst().getState().getHistories().getFirst()).isNotEqualTo(taskRun.getState().getHistories().getFirst());
assertThat(taskRun.getAttempts().getFirst().getState().getCurrent(), is(State.Type.KILLED)); assertThat(taskRun.getAttempts().getFirst().getState().getCurrent()).isEqualTo(State.Type.KILLED);
} }
@Test @Test
@@ -49,9 +47,9 @@ class TaskRunTest {
.build() .build()
.onRunningResend(); .onRunningResend();
assertThat(taskRun.getAttempts().size(), is(2)); assertThat(taskRun.getAttempts().size()).isEqualTo(2);
assertThat(taskRun.getAttempts().get(1).getState().getHistories().getFirst(), is(not(taskRun.getState().getHistories().getFirst()))); assertThat(taskRun.getAttempts().get(1).getState().getHistories().getFirst()).isNotEqualTo(taskRun.getState().getHistories().getFirst());
assertThat(taskRun.getAttempts().get(1).getState().getCurrent(), is(State.Type.KILLED)); assertThat(taskRun.getAttempts().get(1).getState().getCurrent()).isEqualTo(State.Type.KILLED);
} }
} }

View File

@@ -4,26 +4,25 @@ import org.junit.jupiter.api.Test;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class FlowIdTest { class FlowIdTest {
@Test @Test
void shouldGetUidWithoutRevision() { void shouldGetUidWithoutRevision() {
String id = FlowId.uidWithoutRevision("tenant", "io.kestra.unittest", "flow-id"); String id = FlowId.uidWithoutRevision("tenant", "io.kestra.unittest", "flow-id");
assertThat(id, is("tenant_io.kestra.unittest_flow-id")); assertThat(id).isEqualTo("tenant_io.kestra.unittest_flow-id");
} }
@Test @Test
void shouldGetUidGivenEmptyRevision() { void shouldGetUidGivenEmptyRevision() {
String id = FlowId.uid("tenant", "io.kestra.unittest", "flow-id", Optional.empty()); String id = FlowId.uid("tenant", "io.kestra.unittest", "flow-id", Optional.empty());
assertThat(id, is("tenant_io.kestra.unittest_flow-id_-1")); assertThat(id).isEqualTo("tenant_io.kestra.unittest_flow-id_-1");
} }
@Test @Test
void shouldGetUidGivenRevision() { void shouldGetUidGivenRevision() {
String id = FlowId.uid("tenant", "io.kestra.unittest", "flow-id", Optional.of(42)); String id = FlowId.uid("tenant", "io.kestra.unittest", "flow-id", Optional.of(42));
assertThat(id, is("tenant_io.kestra.unittest_flow-id_42")); assertThat(id).isEqualTo("tenant_io.kestra.unittest_flow-id_42");
} }
} }

View File

@@ -20,8 +20,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
class FlowTest { class FlowTest {
@@ -34,11 +33,11 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/duplicate.yaml"); Flow flow = this.parse("flows/invalids/duplicate.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("Duplicate task id with name [date, listen]")); assertThat(validate.get().getMessage()).contains("Duplicate task id with name [date, listen]");
assertThat(validate.get().getMessage(), containsString("Duplicate trigger id with name [trigger]")); assertThat(validate.get().getMessage()).contains("Duplicate trigger id with name [trigger]");
} }
@Test @Test
@@ -46,10 +45,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/duplicate-inputs.yaml"); Flow flow = this.parse("flows/invalids/duplicate-inputs.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("Duplicate input with name [first_input]")); assertThat(validate.get().getMessage()).contains("Duplicate input with name [first_input]");
} }
@Test @Test
@@ -57,10 +56,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/duplicate-parallel.yaml"); Flow flow = this.parse("flows/invalids/duplicate-parallel.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("Duplicate task id with name [t3]")); assertThat(validate.get().getMessage()).contains("Duplicate task id with name [t3]");
} }
@Test @Test
@@ -69,10 +68,10 @@ class FlowTest {
Flow updated = this.parse("flows/invalids/duplicate.yaml"); Flow updated = this.parse("flows/invalids/duplicate.yaml");
Optional<ConstraintViolationException> validate = flow.validateUpdate(updated); Optional<ConstraintViolationException> validate = flow.validateUpdate(updated);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("Illegal flow id update")); assertThat(validate.get().getMessage()).contains("Illegal flow id update");
} }
@@ -81,10 +80,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/switch-invalid.yaml"); Flow flow = this.parse("flows/invalids/switch-invalid.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("impossible: No task defined, neither cases or default have any tasks")); assertThat(validate.get().getMessage()).contains("impossible: No task defined, neither cases or default have any tasks");
} }
@Test @Test
@@ -92,10 +91,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/workingdirectory-invalid.yaml"); Flow flow = this.parse("flows/invalids/workingdirectory-invalid.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("impossible: Only runnable tasks are allowed as children of a WorkingDirectory task")); assertThat(validate.get().getMessage()).contains("impossible: Only runnable tasks are allowed as children of a WorkingDirectory task");
} }
@Test @Test
@@ -103,10 +102,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/workingdirectory-no-tasks.yaml"); Flow flow = this.parse("flows/invalids/workingdirectory-no-tasks.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), containsString("impossible: The 'tasks' property cannot be empty")); assertThat(validate.get().getMessage()).contains("impossible: The 'tasks' property cannot be empty");
} }
@Test @Test
@@ -122,7 +121,7 @@ class FlowTest {
Task findUpdated = updated.findTaskByTaskId("1-2-2_return"); Task findUpdated = updated.findTaskByTaskId("1-2-2_return");
assertThat(((Return) findUpdated).getFormat().toString(), is("{{task.id}}")); assertThat(((Return) findUpdated).getFormat().toString()).isEqualTo("{{task.id}}");
} }
@Test @Test
@@ -130,10 +129,10 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/worker-group.yaml"); Flow flow = this.parse("flows/invalids/worker-group.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(1)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(1);
assertThat(validate.get().getMessage(), equalTo("tasks[0].workerGroup: Worker Group is an Enterprise Edition functionality\n")); assertThat(validate.get().getMessage()).isEqualTo("tasks[0].workerGroup: Worker Group is an Enterprise Edition functionality\n");
} }
@Test @Test
@@ -141,7 +140,7 @@ class FlowTest {
Flow flow = this.parse("flows/valids/trigger-flow-listener-no-inputs.yaml"); Flow flow = this.parse("flows/valids/trigger-flow-listener-no-inputs.yaml");
List<String> all = flow.allTasksWithChildsAndTriggerIds(); List<String> all = flow.allTasksWithChildsAndTriggerIds();
assertThat(all.size(), is(3)); assertThat(all.size()).isEqualTo(3);
} }
@Test @Test
@@ -149,11 +148,11 @@ class FlowTest {
Flow flow = this.parse("flows/invalids/inputs-validation.yaml"); Flow flow = this.parse("flows/invalids/inputs-validation.yaml");
Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); Optional<ConstraintViolationException> validate = modelValidator.isValid(flow);
assertThat(validate.isPresent(), is(true)); assertThat(validate.isPresent()).isEqualTo(true);
assertThat(validate.get().getConstraintViolations().size(), is(2)); assertThat(validate.get().getConstraintViolations().size()).isEqualTo(2);
assertThat(validate.get().getMessage(), containsString("file: no `defaults` can be set for inputs of type 'FILE'")); assertThat(validate.get().getMessage()).contains("file: no `defaults` can be set for inputs of type 'FILE'");
assertThat(validate.get().getMessage(), containsString("array: `itemType` cannot be `ARRAY")); assertThat(validate.get().getMessage()).contains("array: `itemType` cannot be `ARRAY");
} }
// This test is done to ensure the equals is checking the right fields and also make sure the Maps orders don't negate the equality even if they are not the same. // This test is done to ensure the equals is checking the right fields and also make sure the Maps orders don't negate the equality even if they are not the same.
@@ -165,13 +164,13 @@ class FlowTest {
triggerInputsReverseOrder.put("c", "d"); triggerInputsReverseOrder.put("c", "d");
triggerInputsReverseOrder.put("a", "b"); triggerInputsReverseOrder.put("a", "b");
Flow flowABis = baseFlow().toBuilder().revision(2).triggers(List.of(io.kestra.plugin.core.trigger.Flow.builder().inputs(triggerInputsReverseOrder).build())).build(); Flow flowABis = baseFlow().toBuilder().revision(2).triggers(List.of(io.kestra.plugin.core.trigger.Flow.builder().inputs(triggerInputsReverseOrder).build())).build();
assertThat(flowA.equalsWithoutRevision(flowABis), is(true)); assertThat(flowA.equalsWithoutRevision(flowABis)).isEqualTo(true);
Flow flowB = baseFlow().toBuilder().id("b").build(); Flow flowB = baseFlow().toBuilder().id("b").build();
assertThat(flowA.equalsWithoutRevision(flowB), is(false)); assertThat(flowA.equalsWithoutRevision(flowB)).isEqualTo(false);
Flow flowAnotherTenant = baseFlow().toBuilder().tenantId("b").build(); Flow flowAnotherTenant = baseFlow().toBuilder().tenantId("b").build();
assertThat(flowA.equalsWithoutRevision(flowAnotherTenant), is(false)); assertThat(flowA.equalsWithoutRevision(flowAnotherTenant)).isEqualTo(false);
} }
private static Flow baseFlow() { private static Flow baseFlow() {

View File

@@ -16,8 +16,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
class FlowWithSourceTest { class FlowWithSourceTest {
@Test @Test
@@ -41,8 +40,8 @@ class FlowWithSourceTest {
String source = flow.getSource(); String source = flow.getSource();
assertThat(source, not(containsString("deleted: false"))); assertThat(source).doesNotContain("deleted: false");
assertThat(source, containsString("format: |\n")); assertThat(source).contains("format: |\n");
} }
@Test @Test
@@ -65,8 +64,8 @@ class FlowWithSourceTest {
String source = flow.getSource(); String source = flow.getSource();
assertThat(source, containsString("message: Hello World")); assertThat(source).contains("message: Hello World");
assertThat(source, containsString(" cron: 0 1 9 * * *")); assertThat(source).contains(" cron: 0 1 9 * * *");
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -135,7 +134,7 @@ class FlowWithSourceTest {
String expectedSource = flow.sourceOrGenerateIfNull() + " # additional comment"; String expectedSource = flow.sourceOrGenerateIfNull() + " # additional comment";
FlowWithSource of = FlowWithSource.of(flow, expectedSource); FlowWithSource of = FlowWithSource.of(flow, expectedSource);
assertThat(of.equalsWithoutRevision(flow), is(true)); assertThat(of.equalsWithoutRevision(flow)).isEqualTo(true);
assertThat(of.getSource(), is(expectedSource)); assertThat(of.getSource()).isEqualTo(expectedSource);
} }
} }

View File

@@ -11,8 +11,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -30,7 +29,7 @@ class ExecutionAssertionSLATest {
Optional<Violation> evaluate = sla.evaluate(runContext, null); Optional<Violation> evaluate = sla.evaluate(runContext, null);
assertTrue(evaluate.isPresent()); assertTrue(evaluate.isPresent());
assertThat(evaluate.get().reason(), is("assertion is false: {{ condition == 'true'}}.")); assertThat(evaluate.get().reason()).isEqualTo("assertion is false: {{ condition == 'true'}}.");
} }
@Test @Test

View File

@@ -9,8 +9,7 @@ import org.junit.jupiter.api.Test;
import java.time.Duration; import java.time.Duration;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.containsString; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -29,8 +28,8 @@ class MaxDurationSLATest {
Optional<Violation> evaluate = maxDurationSLA.evaluate(null, execution); Optional<Violation> evaluate = maxDurationSLA.evaluate(null, execution);
assertTrue(evaluate.isPresent()); assertTrue(evaluate.isPresent());
assertThat(evaluate.get().reason(), containsString("execution duration of")); assertThat(evaluate.get().reason()).contains("execution duration of");
assertThat(evaluate.get().reason(), containsString("exceed the maximum duration of PT0.05S.")); assertThat(evaluate.get().reason()).contains("exceed the maximum duration of PT0.05S.");
} }
@Test @Test

View File

@@ -31,8 +31,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
class FlowGraphTest { class FlowGraphTest {
@@ -51,17 +50,17 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/return.yaml"); FlowWithSource flow = this.parse("flows/valids/return.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(5)); assertThat(flowGraph.getNodes().size()).isEqualTo(5);
assertThat(flowGraph.getEdges().size(), is(4)); assertThat(flowGraph.getEdges().size()).isEqualTo(4);
assertThat(flowGraph.getClusters().size(), is(0)); assertThat(flowGraph.getClusters().size()).isEqualTo(0);
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getTask().getId(), is("date")); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getTask().getId()).isEqualTo("date");
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getValues(), is(nullValue())); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(2)).getValues()).isNull();
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getTask().getId(), is("task-id")); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getTask().getId()).isEqualTo("task-id");
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getValues(), is(nullValue())); assertThat(((AbstractGraphTask) flowGraph.getNodes().get(3)).getValues()).isNull();
} }
@Test @Test
@@ -69,15 +68,15 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/sequential.yaml"); FlowWithSource flow = this.parse("flows/valids/sequential.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(19)); assertThat(flowGraph.getNodes().size()).isEqualTo(19);
assertThat(flowGraph.getEdges().size(), is(18)); assertThat(flowGraph.getEdges().size()).isEqualTo(18);
assertThat(flowGraph.getClusters().size(), is(3)); assertThat(flowGraph.getClusters().size()).isEqualTo(3);
assertThat(edge(flowGraph, ".*1-3-2-1").getTarget(), matchesPattern(".*1-3-2-2_end")); assertThat(edge(flowGraph, ".*1-3-2-1").getTarget()).matches(".*1-3-2-2_end");
assertThat(edge(flowGraph, ".*1-3-2-1").getRelation().getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(edge(flowGraph, ".*1-3-2-1").getRelation().getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
assertThat(edge(flowGraph, ".*1-seq").getTarget(), matchesPattern(".*1-1")); assertThat(edge(flowGraph, ".*1-seq").getTarget()).matches(".*1-1");
assertThat(edge(flowGraph, ".*1-3-2_seq").getTarget(), matchesPattern(".*1-3-2-1")); assertThat(edge(flowGraph, ".*1-3-2_seq").getTarget()).matches(".*1-3-2-1");
} }
@Test @Test
@@ -85,12 +84,12 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/errors.yaml"); FlowWithSource flow = this.parse("flows/valids/errors.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(17)); assertThat(flowGraph.getNodes().size()).isEqualTo(17);
assertThat(flowGraph.getEdges().size(), is(17)); assertThat(flowGraph.getEdges().size()).isEqualTo(17);
assertThat(flowGraph.getClusters().size(), is(4)); assertThat(flowGraph.getClusters().size()).isEqualTo(4);
assertThat(edge(flowGraph, cluster(flowGraph, "root").getStart(), ".*t2").getRelation().getRelationType(), is(RelationType.ERROR)); assertThat(edge(flowGraph, cluster(flowGraph, "root").getStart(), ".*t2").getRelation().getRelationType()).isEqualTo(RelationType.ERROR);
assertThat(edge(flowGraph, cluster(flowGraph, "root").getStart(), ".*failed").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, cluster(flowGraph, "root").getStart(), ".*failed").getRelation().getRelationType()).isNull();
} }
@Test @Test
@@ -98,16 +97,16 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/parallel.yaml"); FlowWithSource flow = this.parse("flows/valids/parallel.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(12)); assertThat(flowGraph.getNodes().size()).isEqualTo(12);
assertThat(flowGraph.getEdges().size(), is(16)); assertThat(flowGraph.getEdges().size()).isEqualTo(16);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
assertThat(edge(flowGraph, ".*parent", ".*t2").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*parent", ".*t2").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*parent", ".*t6").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*parent", ".*t6").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
String parallelEnd = cluster(flowGraph, "root\\.parent").getEnd(); String parallelEnd = cluster(flowGraph, "root\\.parent").getEnd();
assertThat(edge(flowGraph, ".*t1", parallelEnd).getSource(), matchesPattern(".*parent\\.t1")); assertThat(edge(flowGraph, ".*t1", parallelEnd).getSource()).matches(".*parent\\.t1");
assertThat(edge(flowGraph, ".*t4", parallelEnd).getSource(), matchesPattern(".*parent\\.t4")); assertThat(edge(flowGraph, ".*t4", parallelEnd).getSource()).matches(".*parent\\.t4");
} }
@Test @Test
@@ -115,13 +114,13 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/parallel-nested.yaml"); FlowWithSource flow = this.parse("flows/valids/parallel-nested.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(19)); assertThat(flowGraph.getNodes().size()).isEqualTo(19);
assertThat(flowGraph.getEdges().size(), is(23)); assertThat(flowGraph.getEdges().size()).isEqualTo(23);
assertThat(flowGraph.getClusters().size(), is(3)); assertThat(flowGraph.getClusters().size()).isEqualTo(3);
assertThat(edge(flowGraph, ".*1_par", ".*1-4_end").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*1_par", ".*1-4_end").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*1_par", cluster(flowGraph, ".*1-3_par").getStart()).getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*1_par", cluster(flowGraph, ".*1-3_par").getStart()).getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*1-3-2_par", ".*1-3-2-1").getRelation().getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(edge(flowGraph, ".*1-3-2_par", ".*1-3-2-1").getRelation().getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
} }
@Test @Test
@@ -129,17 +128,17 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/switch.yaml"); FlowWithSource flow = this.parse("flows/valids/switch.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(17)); assertThat(flowGraph.getNodes().size()).isEqualTo(17);
assertThat(flowGraph.getEdges().size(), is(20)); assertThat(flowGraph.getEdges().size()).isEqualTo(20);
assertThat(flowGraph.getClusters().size(), is(3)); assertThat(flowGraph.getClusters().size()).isEqualTo(3);
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.[^.]*").getRelation().getRelationType(), is(RelationType.CHOICE)); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.[^.]*").getRelation().getRelationType()).isEqualTo(RelationType.CHOICE);
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t3\\.[^.]*").getRelation().getValue(), is("THIRD")); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t3\\.[^.]*").getRelation().getValue()).isEqualTo("THIRD");
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t1").getRelation().getRelationType(), is(RelationType.CHOICE)); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t1").getRelation().getRelationType()).isEqualTo(RelationType.CHOICE);
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t1").getRelation().getValue(), is("FIRST")); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.t1").getRelation().getValue()).isEqualTo("FIRST");
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.default").getRelation().getRelationType(), is(RelationType.CHOICE)); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.default").getRelation().getRelationType()).isEqualTo(RelationType.CHOICE);
assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.default").getRelation().getValue(), is("defaults")); assertThat(edge(flowGraph, ".*parent-seq", ".*parent-seq\\.default").getRelation().getValue()).isEqualTo("defaults");
assertThat(edge(flowGraph, ".*t2", ".*t2_sub").getRelation().getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(edge(flowGraph, ".*t2", ".*t2_sub").getRelation().getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
} }
@Test @Test
@@ -147,12 +146,12 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/each-sequential-nested.yaml"); FlowWithSource flow = this.parse("flows/valids/each-sequential-nested.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(13)); assertThat(flowGraph.getNodes().size()).isEqualTo(13);
assertThat(flowGraph.getEdges().size(), is(12)); assertThat(flowGraph.getEdges().size()).isEqualTo(12);
assertThat(flowGraph.getClusters().size(), is(2)); assertThat(flowGraph.getClusters().size()).isEqualTo(2);
assertThat(edge(flowGraph, ".*1-1_return", cluster(flowGraph, ".*1-2_each").getStart()).getRelation().getRelationType(), is(RelationType.DYNAMIC)); assertThat(edge(flowGraph, ".*1-1_return", cluster(flowGraph, ".*1-2_each").getStart()).getRelation().getRelationType()).isEqualTo(RelationType.DYNAMIC);
assertThat(edge(flowGraph, ".*1-2_each", ".*1-2-1_return").getRelation().getRelationType(), is(RelationType.DYNAMIC)); assertThat(edge(flowGraph, ".*1-2_each", ".*1-2-1_return").getRelation().getRelationType()).isEqualTo(RelationType.DYNAMIC);
} }
@Test @Test
@@ -160,12 +159,12 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/each-parallel-nested.yaml"); FlowWithSource flow = this.parse("flows/valids/each-parallel-nested.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(11)); assertThat(flowGraph.getNodes().size()).isEqualTo(11);
assertThat(flowGraph.getEdges().size(), is(10)); assertThat(flowGraph.getEdges().size()).isEqualTo(10);
assertThat(flowGraph.getClusters().size(), is(2)); assertThat(flowGraph.getClusters().size()).isEqualTo(2);
assertThat(edge(flowGraph, ".*1_each", cluster(flowGraph, ".*2-1_seq").getStart()).getRelation().getRelationType(), is(RelationType.DYNAMIC)); assertThat(edge(flowGraph, ".*1_each", cluster(flowGraph, ".*2-1_seq").getStart()).getRelation().getRelationType()).isEqualTo(RelationType.DYNAMIC);
assertThat(flowGraph.getClusters().get(1).getNodes().size(), is(5)); assertThat(flowGraph.getClusters().get(1).getNodes().size()).isEqualTo(5);
} }
@Test @Test
@@ -173,9 +172,9 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/all-flowable.yaml"); FlowWithSource flow = this.parse("flows/valids/all-flowable.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(38)); assertThat(flowGraph.getNodes().size()).isEqualTo(38);
assertThat(flowGraph.getEdges().size(), is(42)); assertThat(flowGraph.getEdges().size()).isEqualTo(42);
assertThat(flowGraph.getClusters().size(), is(7)); assertThat(flowGraph.getClusters().size()).isEqualTo(7);
} }
@Test @Test
@@ -184,18 +183,18 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/parallel.yaml"); FlowWithSource flow = this.parse("flows/valids/parallel.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, execution); FlowGraph flowGraph = GraphUtils.flowGraph(flow, execution);
assertThat(flowGraph.getNodes().size(), is(12)); assertThat(flowGraph.getNodes().size()).isEqualTo(12);
assertThat(flowGraph.getEdges().size(), is(16)); assertThat(flowGraph.getEdges().size()).isEqualTo(16);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
assertThat(edge(flowGraph, ".*parent", ".*t2").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*parent", ".*t2").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*parent", ".*t6").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*parent", ".*t6").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*t1", ((GraphCluster) flowGraph.getClusters().getFirst().getCluster()).getEnd().getUid()).getSource(), matchesPattern(".*t1")); assertThat(edge(flowGraph, ".*t1", ((GraphCluster) flowGraph.getClusters().getFirst().getCluster()).getEnd().getUid()).getSource()).matches(".*t1");
assertThat(edge(flowGraph, ".*t4", ((GraphCluster) flowGraph.getClusters().getFirst().getCluster()).getEnd().getUid()).getSource(), matchesPattern(".*t4")); assertThat(edge(flowGraph, ".*t4", ((GraphCluster) flowGraph.getClusters().getFirst().getCluster()).getEnd().getUid()).getSource()).matches(".*t4");
assertThat(((AbstractGraphTask) node(flowGraph, "t1")).getTaskRun(), is(notNullValue())); assertThat(((AbstractGraphTask) node(flowGraph, "t1")).getTaskRun()).isNotNull();
assertThat(((AbstractGraphTask) node(flowGraph, "t4")).getTaskRun(), is(notNullValue())); assertThat(((AbstractGraphTask) node(flowGraph, "t4")).getTaskRun()).isNotNull();
} }
@Test @Test
@@ -204,15 +203,15 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/each-sequential.yaml"); FlowWithSource flow = this.parse("flows/valids/each-sequential.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, execution); FlowGraph flowGraph = GraphUtils.flowGraph(flow, execution);
assertThat(flowGraph.getNodes().size(), is(21)); assertThat(flowGraph.getNodes().size()).isEqualTo(21);
assertThat(flowGraph.getEdges().size(), is(22)); assertThat(flowGraph.getEdges().size()).isEqualTo(22);
assertThat(flowGraph.getClusters().size(), is(4)); assertThat(flowGraph.getClusters().size()).isEqualTo(4);
assertThat(edge(flowGraph, ".*1-1_value 1", ".*1-1_value 2").getRelation().getValue(), is("value 2")); assertThat(edge(flowGraph, ".*1-1_value 1", ".*1-1_value 2").getRelation().getValue()).isEqualTo("value 2");
assertThat(edge(flowGraph, ".*1-1_value 2", ".*1-1_value 3").getRelation().getValue(), is("value 3")); assertThat(edge(flowGraph, ".*1-1_value 2", ".*1-1_value 3").getRelation().getValue()).isEqualTo("value 3");
assertThat(edge(flowGraph, ".*1-2_value 3", cluster(flowGraph, ".*1_each\\.failed", "value 3").getEnd()), is(notNullValue())); assertThat(edge(flowGraph, ".*1-2_value 3", cluster(flowGraph, ".*1_each\\.failed", "value 3").getEnd())).isNotNull();
assertThat(edge(flowGraph, ".*failed_value 1", ".*1-2_value 1").getTarget(), matchesPattern(".*1-2_value 1")); assertThat(edge(flowGraph, ".*failed_value 1", ".*1-2_value 1").getTarget()).matches(".*1-2_value 1");
} }
@Test @Test
@@ -224,11 +223,11 @@ class FlowGraphTest {
FlowGraph flowGraph = graphService.flowGraph(flow, null); FlowGraph flowGraph = graphService.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(6)); assertThat(flowGraph.getNodes().size()).isEqualTo(6);
assertThat(flowGraph.getEdges().size(), is(5)); assertThat(flowGraph.getEdges().size()).isEqualTo(5);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
AbstractGraph triggerGraph = flowGraph.getNodes().stream().filter(e -> e instanceof GraphTrigger).findFirst().orElseThrow(); AbstractGraph triggerGraph = flowGraph.getNodes().stream().filter(e -> e instanceof GraphTrigger).findFirst().orElseThrow();
assertThat(((GraphTrigger) triggerGraph).getTrigger().getDisabled(), is(true)); assertThat(((GraphTrigger) triggerGraph).getTrigger().getDisabled()).isEqualTo(true);
} }
@Test @Test
@@ -236,9 +235,9 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/trigger-flow-listener-no-inputs.yaml"); FlowWithSource flow = this.parse("flows/valids/trigger-flow-listener-no-inputs.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(7)); assertThat(flowGraph.getNodes().size()).isEqualTo(7);
assertThat(flowGraph.getEdges().size(), is(7)); assertThat(flowGraph.getEdges().size()).isEqualTo(7);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
} }
@@ -247,16 +246,16 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/dag.yaml"); FlowWithSource flow = this.parse("flows/valids/dag.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(11)); assertThat(flowGraph.getNodes().size()).isEqualTo(11);
assertThat(flowGraph.getEdges().size(), is(13)); assertThat(flowGraph.getEdges().size()).isEqualTo(13);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
assertThat(edge(flowGraph, ".*root..*", ".*dag.root..*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*root..*", ".*dag.root..*").getRelation().getRelationType()).isNull();
assertThat(edge(flowGraph, ".*root.dag.*", ".*dag.task1.*").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*root.dag.*", ".*dag.task1.*").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*dag.task2.*", ".*dag.task4.*").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*dag.task2.*", ".*dag.task4.*").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*dag.task2.*", ".*dag.task6.*").getRelation().getRelationType(), is(RelationType.PARALLEL)); assertThat(edge(flowGraph, ".*dag.task2.*", ".*dag.task6.*").getRelation().getRelationType()).isEqualTo(RelationType.PARALLEL);
assertThat(edge(flowGraph, ".*dag.task6", ".*dag.end.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*dag.task6", ".*dag.end.*").getRelation().getRelationType()).isNull();
assertThat(edge(flowGraph, ".*dag.task5", ".*dag.end.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*dag.task5", ".*dag.end.*").getRelation().getRelationType()).isNull();
} }
@Test @Test
@@ -266,29 +265,29 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/task-flow.yaml"); FlowWithSource flow = this.parse("flows/valids/task-flow.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(6)); assertThat(flowGraph.getNodes().size()).isEqualTo(6);
assertThat(flowGraph.getEdges().size(), is(5)); assertThat(flowGraph.getEdges().size()).isEqualTo(5);
assertThat(flowGraph.getClusters().size(), is(1)); assertThat(flowGraph.getClusters().size()).isEqualTo(1);
flowGraph = graphService.flowGraph(flow, Collections.singletonList("root.launch")); flowGraph = graphService.flowGraph(flow, Collections.singletonList("root.launch"));
assertThat(flowGraph.getNodes().size(), is(23)); assertThat(flowGraph.getNodes().size()).isEqualTo(23);
assertThat(flowGraph.getEdges().size(), is(26)); assertThat(flowGraph.getEdges().size()).isEqualTo(26);
assertThat(flowGraph.getClusters().size(), is(5)); assertThat(flowGraph.getClusters().size()).isEqualTo(5);
assertThat(((SubflowGraphTask) ((SubflowGraphCluster) cluster(flowGraph, "root\\.launch").getCluster()).getTaskNode()).executableTask().subflowId().flowId(), is("switch")); assertThat(((SubflowGraphTask) ((SubflowGraphCluster) cluster(flowGraph, "root\\.launch").getCluster()).getTaskNode()).executableTask().subflowId().flowId()).isEqualTo("switch");
SubflowGraphTask subflowGraphTask = (SubflowGraphTask) nodeByUid(flowGraph, "root.launch"); SubflowGraphTask subflowGraphTask = (SubflowGraphTask) nodeByUid(flowGraph, "root.launch");
assertThat(subflowGraphTask.getTask(), instanceOf(SubflowGraphTask.SubflowTaskWrapper.class)); assertThat(subflowGraphTask.getTask()).isInstanceOf(SubflowGraphTask.SubflowTaskWrapper.class);
assertThat(subflowGraphTask.getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(subflowGraphTask.getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
GraphTask switchNode = (GraphTask) nodeByUid(flowGraph, "root.launch.parent-seq"); GraphTask switchNode = (GraphTask) nodeByUid(flowGraph, "root.launch.parent-seq");
assertThat(switchNode.getTask(), instanceOf(Switch.class)); assertThat(switchNode.getTask()).isInstanceOf(Switch.class);
assertThat(switchNode.getRelationType(), is(RelationType.CHOICE)); assertThat(switchNode.getRelationType()).isEqualTo(RelationType.CHOICE);
GraphTrigger flowTrigger = (GraphTrigger) nodeByUid(flowGraph, "root.Triggers.schedule"); GraphTrigger flowTrigger = (GraphTrigger) nodeByUid(flowGraph, "root.Triggers.schedule");
assertThat(flowTrigger.getTriggerDeclaration(), instanceOf(Schedule.class)); assertThat(flowTrigger.getTriggerDeclaration()).isInstanceOf(Schedule.class);
GraphTrigger subflowTrigger = (GraphTrigger) nodeByUid(flowGraph, "root.launch.Triggers.schedule"); GraphTrigger subflowTrigger = (GraphTrigger) nodeByUid(flowGraph, "root.launch.Triggers.schedule");
assertThat(subflowTrigger.getTriggerDeclaration(), instanceOf(Schedule.class)); assertThat(subflowTrigger.getTriggerDeclaration()).isInstanceOf(Schedule.class);
} }
@Test @Test
@@ -298,7 +297,7 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/task-flow-dynamic.yaml").toBuilder().revision(1).build(); FlowWithSource flow = this.parse("flows/valids/task-flow-dynamic.yaml").toBuilder().revision(1).build();
IllegalArgumentException illegalArgumentException = Assertions.assertThrows(IllegalArgumentException.class, () -> graphService.flowGraph(flow, Collections.singletonList("root.launch"))); IllegalArgumentException illegalArgumentException = Assertions.assertThrows(IllegalArgumentException.class, () -> graphService.flowGraph(flow, Collections.singletonList("root.launch")));
assertThat(illegalArgumentException.getMessage(), is("Can't expand subflow task 'launch' because namespace and/or flowId contains dynamic values. This can only be viewed on an execution.")); assertThat(illegalArgumentException.getMessage()).isEqualTo("Can't expand subflow task 'launch' because namespace and/or flowId contains dynamic values. This can only be viewed on an execution.");
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-flow-dynamic", 1, (f, e) -> Map.of( Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-flow-dynamic", 1, (f, e) -> Map.of(
"namespace", f.getNamespace(), "namespace", f.getNamespace(),
@@ -306,9 +305,9 @@ class FlowGraphTest {
)); ));
FlowGraph flowGraph = graphService.flowGraph(flow, Collections.singletonList("root.launch"), execution); FlowGraph flowGraph = graphService.flowGraph(flow, Collections.singletonList("root.launch"), execution);
assertThat(flowGraph.getNodes().size(), is(20)); assertThat(flowGraph.getNodes().size()).isEqualTo(20);
assertThat(flowGraph.getEdges().size(), is(23)); assertThat(flowGraph.getEdges().size()).isEqualTo(23);
assertThat(flowGraph.getClusters().size(), is(4)); assertThat(flowGraph.getClusters().size()).isEqualTo(4);
} }
@Test @Test
@@ -316,13 +315,13 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/finally-sequential.yaml"); FlowWithSource flow = this.parse("flows/valids/finally-sequential.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(13)); assertThat(flowGraph.getNodes().size()).isEqualTo(13);
assertThat(flowGraph.getEdges().size(), is(13)); assertThat(flowGraph.getEdges().size()).isEqualTo(13);
assertThat(flowGraph.getClusters().size(), is(2)); assertThat(flowGraph.getClusters().size()).isEqualTo(2);
assertThat(edge(flowGraph, ".*seq.finally.*", ".*seq.a1").getRelation().getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(edge(flowGraph, ".*seq.finally.*", ".*seq.a1").getRelation().getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
assertThat(edge(flowGraph, ".*seq.a1", ".*seq.a2").getRelation().getRelationType(), is(RelationType.FINALLY)); assertThat(edge(flowGraph, ".*seq.a1", ".*seq.a2").getRelation().getRelationType()).isEqualTo(RelationType.FINALLY);
assertThat(edge(flowGraph, ".*seq.a2", ".*seq.end.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*seq.a2", ".*seq.end.*").getRelation().getRelationType()).isNull();
} }
@Test @Test
@@ -330,15 +329,15 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/finally-sequential-error.yaml"); FlowWithSource flow = this.parse("flows/valids/finally-sequential-error.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(15)); assertThat(flowGraph.getNodes().size()).isEqualTo(15);
assertThat(flowGraph.getEdges().size(), is(16)); assertThat(flowGraph.getEdges().size()).isEqualTo(16);
assertThat(flowGraph.getClusters().size(), is(2)); assertThat(flowGraph.getClusters().size()).isEqualTo(2);
assertThat(edge(flowGraph, ".*seq.e1", ".*seq.e2").getRelation().getRelationType(), is(RelationType.ERROR)); assertThat(edge(flowGraph, ".*seq.e1", ".*seq.e2").getRelation().getRelationType()).isEqualTo(RelationType.ERROR);
assertThat(edge(flowGraph, ".*seq.e2", ".*seq.finally.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*seq.e2", ".*seq.finally.*").getRelation().getRelationType()).isNull();
assertThat(edge(flowGraph, ".*seq.finally.*", ".*seq.a1").getRelation().getRelationType(), is(RelationType.SEQUENTIAL)); assertThat(edge(flowGraph, ".*seq.finally.*", ".*seq.a1").getRelation().getRelationType()).isEqualTo(RelationType.SEQUENTIAL);
assertThat(edge(flowGraph, ".*seq.a1", ".*seq.a2").getRelation().getRelationType(), is(RelationType.FINALLY)); assertThat(edge(flowGraph, ".*seq.a1", ".*seq.a2").getRelation().getRelationType()).isEqualTo(RelationType.FINALLY);
assertThat(edge(flowGraph, ".*seq.a2", ".*seq.end.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*seq.a2", ".*seq.end.*").getRelation().getRelationType()).isNull();
} }
@Test @Test
@@ -346,16 +345,16 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/finally-dag.yaml"); FlowWithSource flow = this.parse("flows/valids/finally-dag.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(17)); assertThat(flowGraph.getNodes().size()).isEqualTo(17);
assertThat(flowGraph.getEdges().size(), is(18)); assertThat(flowGraph.getEdges().size()).isEqualTo(18);
assertThat(flowGraph.getClusters().size(), is(2)); assertThat(flowGraph.getClusters().size()).isEqualTo(2);
assertThat(edge(flowGraph, ".*dag.e1", ".*dag.e2").getRelation().getRelationType(), is(RelationType.ERROR)); assertThat(edge(flowGraph, ".*dag.e1", ".*dag.e2").getRelation().getRelationType()).isEqualTo(RelationType.ERROR);
assertThat(edge(flowGraph, ".*dag.e2", ".*dag.finally.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*dag.e2", ".*dag.finally.*").getRelation().getRelationType()).isNull();
assertThat(edge(flowGraph, ".*dag.t3.end..*", ".*dag.finally.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*dag.t3.end..*", ".*dag.finally.*").getRelation().getRelationType()).isNull();
assertThat(edge(flowGraph, ".*dag.finally.*", ".*dag.a1").getRelation().getRelationType(), is(RelationType.DYNAMIC)); assertThat(edge(flowGraph, ".*dag.finally.*", ".*dag.a1").getRelation().getRelationType()).isEqualTo(RelationType.DYNAMIC);
assertThat(edge(flowGraph, ".*dag.a1", ".*dag.a2").getRelation().getRelationType(), is(RelationType.DYNAMIC)); assertThat(edge(flowGraph, ".*dag.a1", ".*dag.a2").getRelation().getRelationType()).isEqualTo(RelationType.DYNAMIC);
assertThat(edge(flowGraph, ".*dag.a2", ".*dag.end.*").getRelation().getRelationType(), is(nullValue())); assertThat(edge(flowGraph, ".*dag.a2", ".*dag.end.*").getRelation().getRelationType()).isNull();
} }
@Test @Test
@@ -363,12 +362,12 @@ class FlowGraphTest {
FlowWithSource flow = this.parse("flows/valids/after-execution.yaml"); FlowWithSource flow = this.parse("flows/valids/after-execution.yaml");
FlowGraph flowGraph = GraphUtils.flowGraph(flow, null); FlowGraph flowGraph = GraphUtils.flowGraph(flow, null);
assertThat(flowGraph.getNodes().size(), is(5)); assertThat(flowGraph.getNodes().size()).isEqualTo(5);
assertThat(flowGraph.getEdges().size(), is(4)); assertThat(flowGraph.getEdges().size()).isEqualTo(4);
assertThat(edge(flowGraph, "root.root.*", "root.hello.*"), notNullValue()); assertThat(edge(flowGraph, "root.root.*", "root.hello.*")).isNotNull();
assertThat(edge(flowGraph, "root.hello.*", "root.after-execution.*"), notNullValue()); assertThat(edge(flowGraph, "root.hello.*", "root.after-execution.*")).isNotNull();
assertThat(edge(flowGraph, "root.after-execution.*", "root.end.*"), notNullValue()); assertThat(edge(flowGraph, "root.after-execution.*", "root.end.*")).isNotNull();
} }
private FlowWithSource parse(String path) throws IOException { private FlowWithSource parse(String path) throws IOException {

View File

@@ -21,8 +21,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import static java.util.Map.entry; import static java.util.Map.entry;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@KestraTest @KestraTest
@@ -74,16 +73,16 @@ class PropertyTest {
var output = task.run(runContext); var output = task.run(runContext);
assertThat(output, notNullValue()); assertThat(output).isNotNull();
assertThat(output.getValue(), is("test - 9 - not-default - PT1M")); assertThat(output.getValue()).isEqualTo("test - 9 - not-default - PT1M");
assertThat(output.getLevel(), is(Level.INFO)); assertThat(output.getLevel()).isEqualTo(Level.INFO);
assertThat(output.getList(), containsInAnyOrder("item1", "item2")); assertThat(output.getList()).containsExactlyInAnyOrder("item1", "item2");
assertThat(output.getMap(), aMapWithSize(2)); assertThat(output.getMap()).hasSize(2);
assertThat(output.getMap().get("key1"), is("value1")); assertThat(output.getMap().get("key1")).isEqualTo("value1");
assertThat(output.getMap().get("key2"), is("value2")); assertThat(output.getMap().get("key2")).isEqualTo("value2");
assertThat(output.getMessages(), hasSize(1)); assertThat(output.getMessages()).hasSize(1);
assertThat(output.getMessages().getFirst().getKey(), is("mapKey")); assertThat(output.getMessages().getFirst().getKey()).isEqualTo("mapKey");
assertThat(output.getMessages().getFirst().getValue(), is("mapValue")); assertThat(output.getMessages().getFirst().getValue()).isEqualTo("mapValue");
} }
@Test @Test
@@ -132,18 +131,18 @@ class PropertyTest {
var output = task.run(runContext); var output = task.run(runContext);
assertThat(output, notNullValue()); assertThat(output).isNotNull();
assertThat(output.getValue(), is("test - 9 - Default Value - PT1M")); assertThat(output.getValue()).isEqualTo("test - 9 - Default Value - PT1M");
assertThat(output.getLevel(), is(Level.INFO)); assertThat(output.getLevel()).isEqualTo(Level.INFO);
assertThat(output.getList(), containsInAnyOrder("item1", "item2")); assertThat(output.getList()).containsExactlyInAnyOrder("item1", "item2");
assertThat(output.getMap(), aMapWithSize(2)); assertThat(output.getMap()).hasSize(2);
assertThat(output.getMap().get("key1"), is("value1")); assertThat(output.getMap().get("key1")).isEqualTo("value1");
assertThat(output.getMap().get("key2"), is("value2")); assertThat(output.getMap().get("key2")).isEqualTo("value2");
assertThat(output.getMessages(), hasSize(2)); assertThat(output.getMessages()).hasSize(2);
assertThat(output.getMessages().getFirst().getKey(), is("mapKey1")); assertThat(output.getMessages().getFirst().getKey()).isEqualTo("mapKey1");
assertThat(output.getMessages().getFirst().getValue(), is("mapValue1")); assertThat(output.getMessages().getFirst().getValue()).isEqualTo("mapValue1");
assertThat(output.getMessages().get(1).getKey(), is("mapKey2")); assertThat(output.getMessages().get(1).getKey()).isEqualTo("mapKey2");
assertThat(output.getMessages().get(1).getValue(), is("mapValue2")); assertThat(output.getMessages().get(1).getValue()).isEqualTo("mapValue2");
} }
@Test @Test
@@ -189,18 +188,18 @@ class PropertyTest {
var output = task.run(runContext); var output = task.run(runContext);
assertThat(output, notNullValue()); assertThat(output).isNotNull();
assertThat(output.getValue(), is("test - 9 - not-default - PT1M")); assertThat(output.getValue()).isEqualTo("test - 9 - not-default - PT1M");
assertThat(output.getLevel(), is(Level.INFO)); assertThat(output.getLevel()).isEqualTo(Level.INFO);
assertThat(output.getList(), containsInAnyOrder("item1", "item2")); assertThat(output.getList()).containsExactlyInAnyOrder("item1", "item2");
assertThat(output.getMap(), aMapWithSize(2)); assertThat(output.getMap()).hasSize(2);
assertThat(output.getMap().get("key1"), is("value1")); assertThat(output.getMap().get("key1")).isEqualTo("value1");
assertThat(output.getMap().get("key2"), is("value2")); assertThat(output.getMap().get("key2")).isEqualTo("value2");
assertThat(output.getMessages(), hasSize(2)); assertThat(output.getMessages()).hasSize(2);
assertThat(output.getMessages().getFirst().getKey(), is("key1")); assertThat(output.getMessages().getFirst().getKey()).isEqualTo("key1");
assertThat(output.getMessages().getFirst().getValue(), is("value1")); assertThat(output.getMessages().getFirst().getValue()).isEqualTo("value1");
assertThat(output.getMessages().get(1).getKey(), is("key2")); assertThat(output.getMessages().get(1).getKey()).isEqualTo("key2");
assertThat(output.getMessages().get(1).getValue(), is("value2")); assertThat(output.getMessages().get(1).getValue()).isEqualTo("value2");
} }
@Test @Test
@@ -265,14 +264,14 @@ class PropertyTest {
)); ));
var exception = assertThrows(ConstraintViolationException.class, () -> task.run(runContext)); var exception = assertThrows(ConstraintViolationException.class, () -> task.run(runContext));
assertThat(exception.getConstraintViolations().size(), is(1)); assertThat(exception.getConstraintViolations().size()).isEqualTo(1);
assertThat(exception.getMessage(), is("number: must be greater than or equal to 0")); assertThat(exception.getMessage()).isEqualTo("number: must be greater than or equal to 0");
} }
@Test @Test
void of() { void of() {
var prop = Property.of(TestObj.builder().key("key").value("value").build()); var prop = Property.of(TestObj.builder().key("key").value("value").build());
assertThat(prop, notNullValue()); assertThat(prop).isNotNull();
} }
@Test @Test
@@ -291,11 +290,11 @@ class PropertyTest {
var output = task.run(runContext); var output = task.run(runContext);
assertThat(output, notNullValue()); assertThat(output).isNotNull();
assertThat(output.getList(), containsInAnyOrder("arrayValue1", "arrayValue2")); assertThat(output.getList()).containsExactlyInAnyOrder("arrayValue1", "arrayValue2");
assertThat(output.getMap(), aMapWithSize(2)); assertThat(output.getMap()).hasSize(2);
assertThat(output.getMap().get("mapKey1"), is("mapValue1")); assertThat(output.getMap().get("mapKey1")).isEqualTo("mapValue1");
assertThat(output.getMap().get("mapKey2"), is("mapValue2")); assertThat(output.getMap().get("mapKey2")).isEqualTo("mapValue2");
} }
@Test @Test
@@ -318,8 +317,8 @@ class PropertyTest {
var output = task.run(runContext); var output = task.run(runContext);
assertThat(output, notNullValue()); assertThat(output).isNotNull();
assertThat(output.getList(), containsInAnyOrder("python test.py --input1 \"item1\" --input2 \"item2\"", "'gs://bucket/table/file_*.csv.gz'")); assertThat(output.getList()).containsExactlyInAnyOrder("python test.py --input1 \"item1\" --input2 \"item2\"", "'gs://bucket/table/file_*.csv.gz'");
} }
@Builder @Builder

View File

@@ -21,6 +21,7 @@ import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@@ -33,10 +34,10 @@ class ScriptServiceTest {
void replaceInternalStorage() throws IOException { void replaceInternalStorage() throws IOException {
var runContext = runContextFactory.of(); var runContext = runContextFactory.of();
var command = ScriptService.replaceInternalStorage(runContext, null, false); var command = ScriptService.replaceInternalStorage(runContext, null, false);
assertThat(command, is("")); assertThat(command).isEqualTo("");
command = ScriptService.replaceInternalStorage(runContext, "my command", false); command = ScriptService.replaceInternalStorage(runContext, "my command", false);
assertThat(command, is("my command")); assertThat(command).isEqualTo("my command");
Path path = Path.of("/tmp/unittest/file.txt"); Path path = Path.of("/tmp/unittest/file.txt");
if (!path.toFile().exists()) { if (!path.toFile().exists()) {
@@ -49,17 +50,17 @@ class ScriptServiceTest {
command = ScriptService.replaceInternalStorage(runContext, "my command with an internal storage file: " + internalStorageUri, false); command = ScriptService.replaceInternalStorage(runContext, "my command with an internal storage file: " + internalStorageUri, false);
Matcher matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(command); Matcher matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(command);
assertThat(matcher.matches(), is(true)); assertThat(matcher.matches()).isEqualTo(true);
Path absoluteLocalFilePath = Path.of(matcher.group(1)); Path absoluteLocalFilePath = Path.of(matcher.group(1));
localFile = absoluteLocalFilePath.toFile(); localFile = absoluteLocalFilePath.toFile();
assertThat(localFile.exists(), is(true)); assertThat(localFile.exists()).isEqualTo(true);
command = ScriptService.replaceInternalStorage(runContext, "my command with an internal storage file: " + internalStorageUri, true); command = ScriptService.replaceInternalStorage(runContext, "my command with an internal storage file: " + internalStorageUri, true);
matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(command); matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(command);
assertThat(matcher.matches(), is(true)); assertThat(matcher.matches()).isEqualTo(true);
String relativePath = matcher.group(1); String relativePath = matcher.group(1);
assertThat(relativePath, not(startsWith("/"))); assertThat(relativePath).doesNotStartWith("/");
assertThat(runContext.workingDir().resolve(Path.of(relativePath)).toFile().exists(), is(true)); assertThat(runContext.workingDir().resolve(Path.of(relativePath)).toFile().exists()).isEqualTo(true);
} finally { } finally {
localFile.delete(); localFile.delete();
path.toFile().delete(); path.toFile().delete();
@@ -89,22 +90,22 @@ class ScriptServiceTest {
), ),
false false
); );
assertThat(commands, not(empty())); assertThat(commands).isNotEmpty();
assertThat(commands.getFirst(), not(is("my command with an internal storage file: " + internalStorageUri))); assertThat(commands.getFirst(), not(is("my command with an internal storage file: " + internalStorageUri)));
Matcher matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(commands.getFirst()); Matcher matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(commands.getFirst());
assertThat(matcher.matches(), is(true)); assertThat(matcher.matches()).isEqualTo(true);
File file = Path.of(matcher.group(1)).toFile(); File file = Path.of(matcher.group(1)).toFile();
assertThat(file.exists(), is(true)); assertThat(file.exists()).isEqualTo(true);
filesToDelete.add(file); filesToDelete.add(file);
assertThat(commands.get(1), is("my command with some additional var usage: " + wdir)); assertThat(commands.get(1)).isEqualTo("my command with some additional var usage: " + wdir);
commands = ScriptService.replaceInternalStorage(runContext, Collections.emptyMap(), List.of("my command with an internal storage file: " + internalStorageUri), true); commands = ScriptService.replaceInternalStorage(runContext, Collections.emptyMap(), List.of("my command with an internal storage file: " + internalStorageUri), true);
matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(commands.getFirst()); matcher = COMMAND_PATTERN_CAPTURE_LOCAL_PATH.matcher(commands.getFirst());
assertThat(matcher.matches(), is(true)); assertThat(matcher.matches()).isEqualTo(true);
file = runContext.workingDir().resolve(Path.of(matcher.group(1))).toFile(); file = runContext.workingDir().resolve(Path.of(matcher.group(1))).toFile();
assertThat(file.exists(), is(true)); assertThat(file.exists()).isEqualTo(true);
filesToDelete.add(file); filesToDelete.add(file);
} catch (IllegalVariableEvaluationException e) { } catch (IllegalVariableEvaluationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -124,7 +125,7 @@ class ScriptServiceTest {
var outputFiles = ScriptService.uploadOutputFiles(runContext, Path.of("/tmp/unittest")); var outputFiles = ScriptService.uploadOutputFiles(runContext, Path.of("/tmp/unittest"));
assertThat(outputFiles, not(anEmptyMap())); assertThat(outputFiles, not(anEmptyMap()));
assertThat(outputFiles.get("file.txt"), is(URI.create("kestra:///file.txt"))); assertThat(outputFiles.get("file.txt")).isEqualTo(URI.create("kestra:///file.txt"));
path.toFile().delete(); path.toFile().delete();
} }
@@ -132,9 +133,9 @@ class ScriptServiceTest {
@Test @Test
void scriptCommands() { void scriptCommands() {
var scriptCommands = ScriptService.scriptCommands(List.of("interpreter"), List.of("beforeCommand"), List.of("command")); var scriptCommands = ScriptService.scriptCommands(List.of("interpreter"), List.of("beforeCommand"), List.of("command"));
assertThat(scriptCommands, hasSize(2)); assertThat(scriptCommands).hasSize(2);
assertThat(scriptCommands.getFirst(), is("interpreter")); assertThat(scriptCommands.getFirst()).isEqualTo("interpreter");
assertThat(scriptCommands.get(1), is("beforeCommand\ncommand")); assertThat(scriptCommands.get(1)).isEqualTo("beforeCommand\ncommand");
} }
@Test @Test
@@ -142,42 +143,42 @@ class ScriptServiceTest {
var runContext = runContext(runContextFactory, "very.very.very.very.very.very.very.very.very.very.very.very.long.namespace"); var runContext = runContext(runContextFactory, "very.very.very.very.very.very.very.very.very.very.very.very.long.namespace");
var labels = ScriptService.labels(runContext, "kestra.io/"); var labels = ScriptService.labels(runContext, "kestra.io/");
assertThat(labels.size(), is(6)); assertThat(labels.size()).isEqualTo(6);
assertThat(labels.get("kestra.io/namespace"), is("very.very.very.very.very.very.very.very.very.very.very.very.lon")); assertThat(labels.get("kestra.io/namespace")).isEqualTo("very.very.very.very.very.very.very.very.very.very.very.very.lon");
assertThat(labels.get("kestra.io/flow-id"), is("flowId")); assertThat(labels.get("kestra.io/flow-id")).isEqualTo("flowId");
assertThat(labels.get("kestra.io/task-id"), is("task")); assertThat(labels.get("kestra.io/task-id")).isEqualTo("task");
assertThat(labels.get("kestra.io/execution-id"), is("executionId")); assertThat(labels.get("kestra.io/execution-id")).isEqualTo("executionId");
assertThat(labels.get("kestra.io/taskrun-id"), is("taskrun")); assertThat(labels.get("kestra.io/taskrun-id")).isEqualTo("taskrun");
assertThat(labels.get("kestra.io/taskrun-attempt"), is("0")); assertThat(labels.get("kestra.io/taskrun-attempt")).isEqualTo("0");
labels = ScriptService.labels(runContext, null, true, true); labels = ScriptService.labels(runContext, null, true, true);
assertThat(labels.size(), is(6)); assertThat(labels.size()).isEqualTo(6);
assertThat(labels.get("namespace"), is("very.very.very.very.very.very.very.very.very.very.very.very.lon")); assertThat(labels.get("namespace")).isEqualTo("very.very.very.very.very.very.very.very.very.very.very.very.lon");
assertThat(labels.get("flow-id"), is("flowid")); assertThat(labels.get("flow-id")).isEqualTo("flowid");
assertThat(labels.get("task-id"), is("task")); assertThat(labels.get("task-id")).isEqualTo("task");
assertThat(labels.get("execution-id"), is("executionid")); assertThat(labels.get("execution-id")).isEqualTo("executionid");
assertThat(labels.get("taskrun-id"), is("taskrun")); assertThat(labels.get("taskrun-id")).isEqualTo("taskrun");
assertThat(labels.get("taskrun-attempt"), is("0")); assertThat(labels.get("taskrun-attempt")).isEqualTo("0");
} }
@Test @Test
void jobName() { void jobName() {
var runContext = runContext(runContextFactory, "namespace"); var runContext = runContext(runContextFactory, "namespace");
String jobName = ScriptService.jobName(runContext); String jobName = ScriptService.jobName(runContext);
assertThat(jobName, startsWith("namespace-flowid-task-")); assertThat(jobName).startsWith("namespace-flowid-task-");
assertThat(jobName.length(), is(27)); assertThat(jobName.length()).isEqualTo(27);
runContext = runContext(runContextFactory, "very.very.very.very.very.very.very.very.very.very.very.very.long.namespace"); runContext = runContext(runContextFactory, "very.very.very.very.very.very.very.very.very.very.very.very.long.namespace");
jobName = ScriptService.jobName(runContext); jobName = ScriptService.jobName(runContext);
assertThat(jobName, startsWith("veryveryveryveryveryveryveryveryveryveryveryverylongnames-")); assertThat(jobName).startsWith("veryveryveryveryveryveryveryveryveryveryveryverylongnames-");
assertThat(jobName.length(), is(63)); assertThat(jobName.length()).isEqualTo(63);
} }
@Test @Test
void normalize() { void normalize() {
assertThat(ScriptService.normalize(null), nullValue()); assertThat(ScriptService.normalize(null)).isNull();
assertThat(ScriptService.normalize("a-normal-string"), is("a-normal-string")); assertThat(ScriptService.normalize("a-normal-string")).isEqualTo("a-normal-string");
assertThat(ScriptService.normalize("very.very.very.very.very.very.very.very.very.very.very.very.long.namespace"), is("very.very.very.very.very.very.very.very.very.very.very.very.lon")); assertThat(ScriptService.normalize("very.very.very.very.very.very.very.very.very.very.very.very.long.namespace")).isEqualTo("very.very.very.very.very.very.very.very.very.very.very.very.lon");
} }
private RunContext runContext(RunContextFactory runContextFactory, String namespace) { private RunContext runContext(RunContextFactory runContextFactory, String namespace) {

View File

@@ -15,8 +15,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public class TaskRunnerTest { public class TaskRunnerTest {
@@ -47,33 +46,33 @@ public class TaskRunnerTest {
); );
RunContext runContext = runContextFactory.of(contextVariables); RunContext runContext = runContextFactory.of(contextVariables);
assertThat(taskRunner.additionalVars(runContext, taskCommands), is(Map.of( assertThat(taskRunner.additionalVars(runContext, taskCommands)).isEqualTo(Map.of(
ScriptService.VAR_BUCKET_PATH, contextVariables.get("runnerBucketPath"), ScriptService.VAR_BUCKET_PATH, contextVariables.get("runnerBucketPath"),
ScriptService.VAR_WORKING_DIR, TaskRunnerAdditional.RUNNER_WORKING_DIR, ScriptService.VAR_WORKING_DIR, TaskRunnerAdditional.RUNNER_WORKING_DIR,
ScriptService.VAR_OUTPUT_DIR, TaskRunnerAdditional.RUNNER_OUTPUT_DIR, ScriptService.VAR_OUTPUT_DIR, TaskRunnerAdditional.RUNNER_OUTPUT_DIR,
contextVariables.get("runnerAdditionalVarKey"), contextVariables.get("runnerAdditionalVarValue"), contextVariables.get("runnerAdditionalVarKey"), contextVariables.get("runnerAdditionalVarValue"),
contextVariables.get("scriptCommandsAdditionalVarKey"), contextVariables.get("scriptCommandsAdditionalVarValue"), contextVariables.get("scriptCommandsAdditionalVarKey"), contextVariables.get("scriptCommandsAdditionalVarValue"),
ADDITIONAL_VAR_KEY, TaskRunnerAdditional.ADDITIONAL_VAR_VALUE ADDITIONAL_VAR_KEY, TaskRunnerAdditional.ADDITIONAL_VAR_VALUE
))); ));
assertThat(taskRunner.env(runContext, taskCommands), is(Map.of( assertThat(taskRunner.env(runContext, taskCommands)).isEqualTo(Map.of(
ScriptService.ENV_BUCKET_PATH, TaskRunnerAdditional.OVERRIDEN_ENV_BUCKET_PATH, ScriptService.ENV_BUCKET_PATH, TaskRunnerAdditional.OVERRIDEN_ENV_BUCKET_PATH,
ScriptService.ENV_WORKING_DIR, TaskRunnerAdditional.OVERRIDEN_ENV_WORKING_DIR, ScriptService.ENV_WORKING_DIR, TaskRunnerAdditional.OVERRIDEN_ENV_WORKING_DIR,
ScriptService.ENV_OUTPUT_DIR, TaskRunnerAdditional.OVERRIDEN_ENV_OUTPUT_DIR, ScriptService.ENV_OUTPUT_DIR, TaskRunnerAdditional.OVERRIDEN_ENV_OUTPUT_DIR,
contextVariables.get("runnerAdditionalEnvKey"), contextVariables.get("runnerAdditionalEnvValue"), contextVariables.get("runnerAdditionalEnvKey"), contextVariables.get("runnerAdditionalEnvValue"),
contextVariables.get("scriptCommandsAdditionalEnvKey"), contextVariables.get("scriptCommandsAdditionalEnvValue"), contextVariables.get("scriptCommandsAdditionalEnvKey"), contextVariables.get("scriptCommandsAdditionalEnvValue"),
ADDITIONAL_ENV_KEY, TaskRunnerAdditional.ADDITIONAL_ENV_VALUE ADDITIONAL_ENV_KEY, TaskRunnerAdditional.ADDITIONAL_ENV_VALUE
))); ));
taskRunner = new TaskRunnerAdditional(false); taskRunner = new TaskRunnerAdditional(false);
assertThat(taskRunner.env(runContext, taskCommands), is(Map.of( assertThat(taskRunner.env(runContext, taskCommands)).isEqualTo(Map.of(
ScriptService.ENV_BUCKET_PATH, contextVariables.get("runnerBucketPath"), ScriptService.ENV_BUCKET_PATH, contextVariables.get("runnerBucketPath"),
ScriptService.ENV_WORKING_DIR, TaskRunnerAdditional.RUNNER_WORKING_DIR, ScriptService.ENV_WORKING_DIR, TaskRunnerAdditional.RUNNER_WORKING_DIR,
ScriptService.ENV_OUTPUT_DIR, TaskRunnerAdditional.RUNNER_OUTPUT_DIR, ScriptService.ENV_OUTPUT_DIR, TaskRunnerAdditional.RUNNER_OUTPUT_DIR,
contextVariables.get("runnerAdditionalEnvKey"), contextVariables.get("runnerAdditionalEnvValue"), contextVariables.get("runnerAdditionalEnvKey"), contextVariables.get("runnerAdditionalEnvValue"),
contextVariables.get("scriptCommandsAdditionalEnvKey"), contextVariables.get("scriptCommandsAdditionalEnvValue"), contextVariables.get("scriptCommandsAdditionalEnvKey"), contextVariables.get("scriptCommandsAdditionalEnvValue"),
ADDITIONAL_ENV_KEY, TaskRunnerAdditional.ADDITIONAL_ENV_VALUE ADDITIONAL_ENV_KEY, TaskRunnerAdditional.ADDITIONAL_ENV_VALUE
))); ));
} }
private static class TaskRunnerAdditional extends TaskRunner<TaskRunnerDetailResult> { private static class TaskRunnerAdditional extends TaskRunner<TaskRunnerDetailResult> {

View File

@@ -20,8 +20,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
public abstract class AbstractMultipleConditionStorageTest { public abstract class AbstractMultipleConditionStorageTest {
@@ -39,13 +38,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
assertThat(window.getStart().toLocalTime(), is(LocalTime.parse("00:00:00"))); assertThat(window.getStart().toLocalTime()).isEqualTo(LocalTime.parse("00:00:00"));
assertThat(window.getStart().toLocalDate(), is(ZonedDateTime.now().toLocalDate())); assertThat(window.getStart().toLocalDate()).isEqualTo(ZonedDateTime.now().toLocalDate());
assertThat(window.getEnd().toLocalTime(), is(LocalTime.parse("23:59:59.999"))); assertThat(window.getEnd().toLocalTime()).isEqualTo(LocalTime.parse("23:59:59.999"));
assertThat(window.getEnd().toLocalDate(), is(ZonedDateTime.now().toLocalDate())); assertThat(window.getEnd().toLocalDate()).isEqualTo(ZonedDateTime.now().toLocalDate());
} }
@Test @Test
@@ -56,13 +55,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
assertThat(window.getStart().toLocalTime(), is(LocalTime.parse("00:00:00"))); assertThat(window.getStart().toLocalTime()).isEqualTo(LocalTime.parse("00:00:00"));
assertThat(window.getStart().toLocalDate(), is(ZonedDateTime.now().toLocalDate())); assertThat(window.getStart().toLocalDate()).isEqualTo(ZonedDateTime.now().toLocalDate());
assertThat(window.getEnd().toLocalTime(), is(LocalTime.parse("23:59:59.999"))); assertThat(window.getEnd().toLocalTime()).isEqualTo(LocalTime.parse("23:59:59.999"));
assertThat(window.getEnd().toLocalDate(), is(ZonedDateTime.now().toLocalDate())); assertThat(window.getEnd().toLocalDate()).isEqualTo(ZonedDateTime.now().toLocalDate());
} }
@Test @Test
@@ -73,13 +72,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
assertThat(window.getStart().toLocalTime(), is(LocalTime.parse("20:00:00"))); assertThat(window.getStart().toLocalTime()).isEqualTo(LocalTime.parse("20:00:00"));
assertThat(window.getStart().toLocalDate(), is(ZonedDateTime.now().minusDays(1).toLocalDate())); assertThat(window.getStart().toLocalDate()).isEqualTo(ZonedDateTime.now().minusDays(1).toLocalDate());
assertThat(window.getEnd().toLocalTime(), is(LocalTime.parse("19:59:59.999"))); assertThat(window.getEnd().toLocalTime()).isEqualTo(LocalTime.parse("19:59:59.999"));
assertThat(window.getEnd().toLocalDate(), is(ZonedDateTime.now().toLocalDate())); assertThat(window.getEnd().toLocalDate()).isEqualTo(ZonedDateTime.now().toLocalDate());
} }
@Test @Test
@@ -90,14 +89,14 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
assertThat(window.getStart().toLocalTime().getHour(), is(ZonedDateTime.now().minusHours(4).getHour())); assertThat(window.getStart().toLocalTime().getHour()).isEqualTo(ZonedDateTime.now().minusHours(4).getHour());
assertThat(window.getStart().toLocalDate(), is(ZonedDateTime.now().minusHours(4).toLocalDate())); assertThat(window.getStart().toLocalDate()).isEqualTo(ZonedDateTime.now().minusHours(4).toLocalDate());
assertThat(window.getEnd().toLocalTime().getHour(), is(ZonedDateTime.now().minusHours(4).getHour())); assertThat(window.getEnd().toLocalTime().getHour()).isEqualTo(ZonedDateTime.now().minusHours(4).getHour());
assertThat(window.getEnd().toLocalTime().getMinute(), is(59)); assertThat(window.getEnd().toLocalTime().getMinute()).isEqualTo(59);
assertThat(window.getEnd().toLocalDate(), is(ZonedDateTime.now().minusHours(4).toLocalDate())); assertThat(window.getEnd().toLocalDate()).isEqualTo(ZonedDateTime.now().minusHours(4).toLocalDate());
} }
@Test @Test
@@ -108,9 +107,9 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
assertThat(window.getStart().getMinute(), is(in(Arrays.asList(10, 25, 40, 55)))); assertThat(window.getStart().getMinute()).isIn(Arrays.asList(10, 25, 40, 55));
assertThat(window.getEnd().getMinute(), is(in(Arrays.asList(9, 24, 39, 54)))); assertThat(window.getEnd().getMinute()).isIn(Arrays.asList(9, 24, 39, 54));
} }
@Test @Test
@@ -121,20 +120,17 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults().get("a"), is(true)); assertThat(window.getResults().get("a")).isEqualTo(true);
Thread.sleep(2005); Thread.sleep(2005);
MultipleConditionWindow next = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow next = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat( assertThat(next.getStart().format(DateTimeFormatter.ISO_DATE_TIME)).isNotEqualTo(window.getStart().format(DateTimeFormatter.ISO_DATE_TIME));
next.getStart().format(DateTimeFormatter.ISO_DATE_TIME), assertThat(next.getResults().containsKey("a")).isEqualTo(false);
is(not(window.getStart().format(DateTimeFormatter.ISO_DATE_TIME)))
);
assertThat(next.getResults().containsKey("a"), is(false));
} }
@Test @Test
@@ -145,18 +141,18 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults().get("a"), is(true)); assertThat(window.getResults().get("a")).isEqualTo(true);
List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null); List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(0)); assertThat(expired.size()).isEqualTo(0);
Thread.sleep(2005); Thread.sleep(2005);
expired = multipleConditionStorage.expired(null); expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(1)); assertThat(expired.size()).isEqualTo(1);
} }
@Test @Test
@@ -167,18 +163,18 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults().get("a"), is(true)); assertThat(window.getResults().get("a")).isEqualTo(true);
List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null); List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(0)); assertThat(expired.size()).isEqualTo(0);
Thread.sleep(2005); Thread.sleep(2005);
expired = multipleConditionStorage.expired(null); expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(1)); assertThat(expired.size()).isEqualTo(1);
} }
@Test @Test
@@ -189,13 +185,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults(), anEmptyMap()); assertThat(window.getResults()).isEmpty();
List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null); List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(1)); assertThat(expired.size()).isEqualTo(1);
} }
@Test @Test
@@ -207,13 +203,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults().get("a"), is(true)); assertThat(window.getResults().get("a")).isEqualTo(true);
List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null); List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(0)); assertThat(expired.size()).isEqualTo(0);
} }
@Test @Test
@@ -224,13 +220,13 @@ public abstract class AbstractMultipleConditionStorageTest {
MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); MultipleConditionWindow window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true)))); this.save(multipleConditionStorage, pair.getLeft(), Collections.singletonList(window.with(ImmutableMap.of("a", true))));
assertThat(window.getFlowId(), is(pair.getLeft().getId())); assertThat(window.getFlowId()).isEqualTo(pair.getLeft().getId());
window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap()); window = multipleConditionStorage.getOrCreate(pair.getKey(), pair.getRight(), Collections.emptyMap());
assertThat(window.getResults().get("a"), is(true)); assertThat(window.getResults().get("a")).isEqualTo(true);
List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null); List<MultipleConditionWindow> expired = multipleConditionStorage.expired(null);
assertThat(expired.size(), is(0)); assertThat(expired.size()).isEqualTo(0);
} }
private static Pair<Flow, MultipleCondition> mockFlow(TimeWindow sla) { private static Pair<Flow, MultipleCondition> mockFlow(TimeWindow sla) {

View File

@@ -2,16 +2,12 @@ package io.kestra.core.plugins;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
public class ClassTypeIdentifierTest { public class ClassTypeIdentifierTest {
@Test @Test
void caseMatters() { void caseMatters() {
String identifier = "io.kestra.core.plugins.serdes.PluginDeserializerTest.TestPlugin"; String identifier = "io.kestra.core.plugins.serdes.PluginDeserializerTest.TestPlugin";
assertThat( assertThat(DefaultPluginRegistry.ClassTypeIdentifier.create(identifier).type()).isEqualTo(identifier);
DefaultPluginRegistry.ClassTypeIdentifier.create(identifier).type(),
is(identifier)
);
} }
} }

View File

@@ -9,8 +9,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static org.hamcrest.CoreMatchers.hasItem; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
@KestraTest @KestraTest
class PluginConfigurationTest { class PluginConfigurationTest {
@@ -20,9 +19,9 @@ class PluginConfigurationTest {
@Test @Test
void testInjectEachProperty() { void testInjectEachProperty() {
assertThat(this.configurations, hasItem(new PluginConfiguration(0, "io.kestra.plugin.Test0", Map.of("prop0", "value0")))); assertThat(this.configurations).contains(new PluginConfiguration(0, "io.kestra.plugin.Test0", Map.of("prop0", "value0")));
assertThat(this.configurations, hasItem(new PluginConfiguration(1, "io.kestra.plugin.Test1", Map.of("prop1", "value1")))); assertThat(this.configurations).contains(new PluginConfiguration(1, "io.kestra.plugin.Test1", Map.of("prop1", "value1")));
assertThat(this.configurations, hasItem(new PluginConfiguration(2, "io.kestra.plugin.Test2", Map.of("prop2", "value2")))); assertThat(this.configurations).contains(new PluginConfiguration(2, "io.kestra.plugin.Test2", Map.of("prop2", "value2")));
} }
} }

View File

@@ -8,8 +8,7 @@ import java.nio.file.Paths;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
class PluginScannerTest { class PluginScannerTest {
@Test @Test
@@ -19,14 +18,14 @@ class PluginScannerTest {
PluginScanner pluginScanner = new PluginScanner(PluginScannerTest.class.getClassLoader()); PluginScanner pluginScanner = new PluginScanner(PluginScannerTest.class.getClassLoader());
List<RegisteredPlugin> scan = pluginScanner.scan(plugins); List<RegisteredPlugin> scan = pluginScanner.scan(plugins);
assertThat(scan.size(), is(1)); assertThat(scan.size()).isEqualTo(1);
assertThat(scan.getFirst().getManifest().getMainAttributes().getValue("X-Kestra-Group"), is("io.kestra.plugin.templates")); assertThat(scan.getFirst().getManifest().getMainAttributes().getValue("X-Kestra-Group")).isEqualTo("io.kestra.plugin.templates");
} }
@Test @Test
void scanCore() { void scanCore() {
PluginScanner pluginScanner = new PluginScanner(PluginScannerTest.class.getClassLoader()); PluginScanner pluginScanner = new PluginScanner(PluginScannerTest.class.getClassLoader());
RegisteredPlugin scan = pluginScanner.scan(); RegisteredPlugin scan = pluginScanner.scan();
assertThat(scan.getManifest().getMainAttributes().getValue("X-Kestra-Group"), is("io.kestra.plugin.core")); assertThat(scan.getManifest().getMainAttributes().getValue("X-Kestra-Group")).isEqualTo("io.kestra.plugin.core");
} }
} }

View File

@@ -35,7 +35,8 @@ import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.*; import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
@@ -145,8 +146,8 @@ public abstract class AbstractExecutionRepositoryTest {
inject(); inject();
ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10), null, null); ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10), null, null);
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
assertThat(executions.size(), is(10)); assertThat(executions.size()).isEqualTo(10);
List<QueryFilter> filters = List.of(QueryFilter.builder() List<QueryFilter> filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.STATE) .field(QueryFilter.Field.STATE)
@@ -154,7 +155,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value( List.of(State.Type.RUNNING, State.Type.FAILED)) .value( List.of(State.Type.RUNNING, State.Type.FAILED))
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(8L)); assertThat(executions.getTotal()).isEqualTo(8L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.LABELS) .field(QueryFilter.Field.LABELS)
@@ -162,7 +163,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value(Map.of("key", "value")) .value(Map.of("key", "value"))
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(1L)); assertThat(executions.getTotal()).isEqualTo(1L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.LABELS) .field(QueryFilter.Field.LABELS)
@@ -170,7 +171,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value(Map.of("key", "value2")) .value(Map.of("key", "value2"))
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(0L)); assertThat(executions.getTotal()).isEqualTo(0L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.LABELS) .field(QueryFilter.Field.LABELS)
@@ -179,7 +180,7 @@ public abstract class AbstractExecutionRepositoryTest {
.build() .build()
); );
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(1L)); assertThat(executions.getTotal()).isEqualTo(1L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.FLOW_ID) .field(QueryFilter.Field.FLOW_ID)
@@ -187,7 +188,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value("second") .value("second")
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(13L)); assertThat(executions.getTotal()).isEqualTo(13L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.FLOW_ID) .field(QueryFilter.Field.FLOW_ID)
@@ -201,7 +202,7 @@ public abstract class AbstractExecutionRepositoryTest {
.build() .build()
); );
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(13L)); assertThat(executions.getTotal()).isEqualTo(13L);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.NAMESPACE) .field(QueryFilter.Field.NAMESPACE)
@@ -209,7 +210,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value("io.kestra") .value("io.kestra")
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
} }
@Test @Test
@@ -225,9 +226,9 @@ public abstract class AbstractExecutionRepositoryTest {
.value(executionTriggerId) .value(executionTriggerId)
.build()); .build());
ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10), null, filters); ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
assertThat(executions.size(), is(10)); assertThat(executions.size()).isEqualTo(10);
assertThat(executions.getFirst().getTrigger().getVariables().get("executionId"), is(executionTriggerId)); assertThat(executions.getFirst().getTrigger().getVariables().get("executionId")).isEqualTo(executionTriggerId);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.CHILD_FILTER) .field(QueryFilter.Field.CHILD_FILTER)
.operation(QueryFilter.Op.EQUALS) .operation(QueryFilter.Op.EQUALS)
@@ -235,9 +236,9 @@ public abstract class AbstractExecutionRepositoryTest {
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
assertThat(executions.size(), is(10)); assertThat(executions.size()).isEqualTo(10);
assertThat(executions.getFirst().getTrigger().getVariables().get("executionId"), is(executionTriggerId)); assertThat(executions.getFirst().getTrigger().getVariables().get("executionId")).isEqualTo(executionTriggerId);
filters = List.of(QueryFilter.builder() filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.CHILD_FILTER) .field(QueryFilter.Field.CHILD_FILTER)
@@ -246,12 +247,12 @@ public abstract class AbstractExecutionRepositoryTest {
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters ); executions = executionRepository.find(Pageable.from(1, 10), null, filters );
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
assertThat(executions.size(), is(10)); assertThat(executions.size()).isEqualTo(10);
assertThat(executions.getFirst().getTrigger(), is(nullValue())); assertThat(executions.getFirst().getTrigger()).isNull();
executions = executionRepository.find(Pageable.from(1, 10), null,null); executions = executionRepository.find(Pageable.from(1, 10), null,null);
assertThat(executions.getTotal(), is(56L)); assertThat(executions.getTotal()).isEqualTo(56L);
} }
@Test @Test
@@ -259,8 +260,8 @@ public abstract class AbstractExecutionRepositoryTest {
inject(); inject();
ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10, Sort.of(Sort.Order.desc("id"))), null, null); ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10, Sort.of(Sort.Order.desc("id"))), null, null);
assertThat(executions.getTotal(), is(28L)); assertThat(executions.getTotal()).isEqualTo(28L);
assertThat(executions.size(), is(10)); assertThat(executions.size()).isEqualTo(10);
var filters = List.of(QueryFilter.builder() var filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.STATE) .field(QueryFilter.Field.STATE)
@@ -268,7 +269,7 @@ public abstract class AbstractExecutionRepositoryTest {
.value(List.of(State.Type.RUNNING, State.Type.FAILED)) .value(List.of(State.Type.RUNNING, State.Type.FAILED))
.build()); .build());
executions = executionRepository.find(Pageable.from(1, 10), null, filters); executions = executionRepository.find(Pageable.from(1, 10), null, filters);
assertThat(executions.getTotal(), is(8L)); assertThat(executions.getTotal()).isEqualTo(8L);
} }
@Test @Test
@@ -276,8 +277,8 @@ public abstract class AbstractExecutionRepositoryTest {
inject(); inject();
ArrayListTotal<TaskRun> taskRuns = executionRepository.findTaskRun(Pageable.from(1, 10), null, null); ArrayListTotal<TaskRun> taskRuns = executionRepository.findTaskRun(Pageable.from(1, 10), null, null);
assertThat(taskRuns.getTotal(), is(71L)); assertThat(taskRuns.getTotal()).isEqualTo(71L);
assertThat(taskRuns.size(), is(10)); assertThat(taskRuns.size()).isEqualTo(10);
var filters = List.of(QueryFilter.builder() var filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.LABELS) .field(QueryFilter.Field.LABELS)
@@ -286,8 +287,8 @@ public abstract class AbstractExecutionRepositoryTest {
.build()); .build());
taskRuns = executionRepository.findTaskRun(Pageable.from(1, 10), null, filters); taskRuns = executionRepository.findTaskRun(Pageable.from(1, 10), null, filters);
assertThat(taskRuns.getTotal(), is(1L)); assertThat(taskRuns.getTotal()).isEqualTo(1L);
assertThat(taskRuns.size(), is(1)); assertThat(taskRuns.size()).isEqualTo(1);
} }
@@ -296,10 +297,10 @@ public abstract class AbstractExecutionRepositoryTest {
executionRepository.save(ExecutionFixture.EXECUTION_1); executionRepository.save(ExecutionFixture.EXECUTION_1);
Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId()); Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
full.ifPresent(current -> { full.ifPresent(current -> {
assertThat(full.get().getId(), is(ExecutionFixture.EXECUTION_1.getId())); assertThat(full.get().getId()).isEqualTo(ExecutionFixture.EXECUTION_1.getId());
}); });
} }
@@ -308,12 +309,12 @@ public abstract class AbstractExecutionRepositoryTest {
executionRepository.save(ExecutionFixture.EXECUTION_1); executionRepository.save(ExecutionFixture.EXECUTION_1);
Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId()); Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
executionRepository.purge(ExecutionFixture.EXECUTION_1); executionRepository.purge(ExecutionFixture.EXECUTION_1);
full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId()); full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId());
assertThat(full.isPresent(), is(false)); assertThat(full.isPresent()).isEqualTo(false);
} }
@Test @Test
@@ -321,12 +322,12 @@ public abstract class AbstractExecutionRepositoryTest {
executionRepository.save(ExecutionFixture.EXECUTION_1); executionRepository.save(ExecutionFixture.EXECUTION_1);
Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId()); Optional<Execution> full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
executionRepository.delete(ExecutionFixture.EXECUTION_1); executionRepository.delete(ExecutionFixture.EXECUTION_1);
full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId()); full = executionRepository.findById(null, ExecutionFixture.EXECUTION_1.getId());
assertThat(full.isPresent(), is(false)); assertThat(full.isPresent()).isEqualTo(false);
} }
@Test @Test
@@ -336,7 +337,7 @@ public abstract class AbstractExecutionRepositoryTest {
ArrayListTotal<Execution> page1 = executionRepository.findByFlowId(null, NAMESPACE, FLOW, Pageable.from(1, 10)); ArrayListTotal<Execution> page1 = executionRepository.findByFlowId(null, NAMESPACE, FLOW, Pageable.from(1, 10));
assertThat(page1.size(), is(2)); assertThat(page1.size()).isEqualTo(2);
} }
@Test @Test
@@ -362,23 +363,23 @@ public abstract class AbstractExecutionRepositoryTest {
false false
); );
assertThat(result.size(), is(1)); assertThat(result.size()).isEqualTo(1);
assertThat(result.get("io.kestra.unittest").size(), is(2)); assertThat(result.get("io.kestra.unittest").size()).isEqualTo(2);
DailyExecutionStatistics full = result.get("io.kestra.unittest").get(FLOW).get(10); DailyExecutionStatistics full = result.get("io.kestra.unittest").get(FLOW).get(10);
DailyExecutionStatistics second = result.get("io.kestra.unittest").get("second").get(10); DailyExecutionStatistics second = result.get("io.kestra.unittest").get("second").get(10);
assertThat(full.getDuration().getAvg().toMillis(), greaterThan(0L)); assertThat(full.getDuration().getAvg().toMillis()).isGreaterThan(0L);
assertThat(full.getExecutionCounts().size(), is(11)); assertThat(full.getExecutionCounts().size()).isEqualTo(11);
assertThat(full.getExecutionCounts().get(State.Type.FAILED), is(3L)); assertThat(full.getExecutionCounts().get(State.Type.FAILED)).isEqualTo(3L);
assertThat(full.getExecutionCounts().get(State.Type.RUNNING), is(5L)); assertThat(full.getExecutionCounts().get(State.Type.RUNNING)).isEqualTo(5L);
assertThat(full.getExecutionCounts().get(State.Type.SUCCESS), is(7L)); assertThat(full.getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(7L);
assertThat(full.getExecutionCounts().get(State.Type.CREATED), is(0L)); assertThat(full.getExecutionCounts().get(State.Type.CREATED)).isEqualTo(0L);
assertThat(second.getDuration().getAvg().toMillis(), greaterThan(0L)); assertThat(second.getDuration().getAvg().toMillis()).isGreaterThan(0L);
assertThat(second.getExecutionCounts().size(), is(11)); assertThat(second.getExecutionCounts().size()).isEqualTo(11);
assertThat(second.getExecutionCounts().get(State.Type.SUCCESS), is(13L)); assertThat(second.getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(13L);
assertThat(second.getExecutionCounts().get(State.Type.CREATED), is(0L)); assertThat(second.getExecutionCounts().get(State.Type.CREATED)).isEqualTo(0L);
result = executionRepository.dailyGroupByFlowStatistics( result = executionRepository.dailyGroupByFlowStatistics(
null, null,
@@ -391,15 +392,15 @@ public abstract class AbstractExecutionRepositoryTest {
true true
); );
assertThat(result.size(), is(1)); assertThat(result.size()).isEqualTo(1);
assertThat(result.get("io.kestra.unittest").size(), is(1)); assertThat(result.get("io.kestra.unittest").size()).isEqualTo(1);
full = result.get("io.kestra.unittest").get("*").get(10); full = result.get("io.kestra.unittest").get("*").get(10);
assertThat(full.getDuration().getAvg().toMillis(), greaterThan(0L)); assertThat(full.getDuration().getAvg().toMillis()).isGreaterThan(0L);
assertThat(full.getExecutionCounts().size(), is(11)); assertThat(full.getExecutionCounts().size()).isEqualTo(11);
assertThat(full.getExecutionCounts().get(State.Type.FAILED), is(3L)); assertThat(full.getExecutionCounts().get(State.Type.FAILED)).isEqualTo(3L);
assertThat(full.getExecutionCounts().get(State.Type.RUNNING), is(5L)); assertThat(full.getExecutionCounts().get(State.Type.RUNNING)).isEqualTo(5L);
assertThat(full.getExecutionCounts().get(State.Type.SUCCESS), is(20L)); assertThat(full.getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(20L);
assertThat(full.getExecutionCounts().get(State.Type.CREATED), is(0L)); assertThat(full.getExecutionCounts().get(State.Type.CREATED)).isEqualTo(0L);
result = executionRepository.dailyGroupByFlowStatistics( result = executionRepository.dailyGroupByFlowStatistics(
null, null,
@@ -412,9 +413,9 @@ public abstract class AbstractExecutionRepositoryTest {
false false
); );
assertThat(result.size(), is(1)); assertThat(result.size()).isEqualTo(1);
assertThat(result.get("io.kestra.unittest").size(), is(1)); assertThat(result.get("io.kestra.unittest").size()).isEqualTo(1);
assertThat(result.get("io.kestra.unittest").get(FLOW).size(), is(11)); assertThat(result.get("io.kestra.unittest").get(FLOW).size()).isEqualTo(11);
} }
@Test @Test
@@ -477,17 +478,16 @@ public abstract class AbstractExecutionRepositoryTest {
) )
); );
assertThat(result.size(), is(2)); assertThat(result.size()).isEqualTo(2);
assertThat(result, containsInAnyOrder( assertThat(result)
allOf( .extracting(
hasProperty("state", hasProperty("current", is(State.Type.FAILED))), r -> r.getState().getCurrent(),
hasProperty("namespace", is(NAMESPACE)) Execution::getNamespace
),
allOf(
hasProperty("state", hasProperty("current", is(State.Type.SUCCESS))),
hasProperty("namespace", is(anotherNamespace))
) )
)); .containsExactlyInAnyOrder(
tuple(State.Type.FAILED, NAMESPACE),
tuple(State.Type.SUCCESS, anotherNamespace)
);
} }
@Test @Test
@@ -519,13 +519,13 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
false); false);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().size(), is(11)); assertThat(result.get(10).getExecutionCounts().size()).isEqualTo(11);
assertThat(result.get(10).getDuration().getAvg().toMillis(), greaterThan(0L)); assertThat(result.get(10).getDuration().getAvg().toMillis()).isGreaterThan(0L);
assertThat(result.get(10).getExecutionCounts().get(State.Type.FAILED), is(3L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.FAILED)).isEqualTo(3L);
assertThat(result.get(10).getExecutionCounts().get(State.Type.RUNNING), is(5L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.RUNNING)).isEqualTo(5L);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(21L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(21L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -539,8 +539,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
false); false);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(21L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(21L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -553,8 +553,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
null, null,
false); false);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(20L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(20L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -567,8 +567,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
null, null,
false); false);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(1L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(1L);
} }
@Test @Test
@@ -597,13 +597,13 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
true); true);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().size(), is(11)); assertThat(result.get(10).getExecutionCounts().size()).isEqualTo(11);
assertThat(result.get(10).getDuration().getAvg().toMillis(), greaterThan(0L)); assertThat(result.get(10).getDuration().getAvg().toMillis()).isGreaterThan(0L);
assertThat(result.get(10).getExecutionCounts().get(State.Type.FAILED), is(3L * 2)); assertThat(result.get(10).getExecutionCounts().get(State.Type.FAILED)).isEqualTo(3L * 2);
assertThat(result.get(10).getExecutionCounts().get(State.Type.RUNNING), is(5L * 2)); assertThat(result.get(10).getExecutionCounts().get(State.Type.RUNNING)).isEqualTo(5L * 2);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(57L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(57L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -617,8 +617,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
true); true);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(57L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(57L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -631,8 +631,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
null, null,
true); true);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(55L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(55L);
result = executionRepository.dailyStatistics( result = executionRepository.dailyStatistics(
null, null,
@@ -645,8 +645,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
null, null,
true); true);
assertThat(result.size(), is(11)); assertThat(result.size()).isEqualTo(11);
assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS), is(2L)); assertThat(result.get(10).getExecutionCounts().get(State.Type.SUCCESS)).isEqualTo(2L);
} }
@SuppressWarnings("OptionalGetWithoutIsPresent") @SuppressWarnings("OptionalGetWithoutIsPresent")
@@ -675,11 +675,11 @@ public abstract class AbstractExecutionRepositoryTest {
ZonedDateTime.now(), ZonedDateTime.now(),
null null
); );
assertThat(result.size(), is(4)); assertThat(result.size()).isEqualTo(4);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("first")).findFirst().get().getCount(), is(2L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("first")).findFirst().get().getCount()).isEqualTo(2L);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("second")).findFirst().get().getCount(), is(3L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("second")).findFirst().get().getCount()).isEqualTo(3L);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("third")).findFirst().get().getCount(), is(9L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("third")).findFirst().get().getCount()).isEqualTo(9L);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("missing")).findFirst().get().getCount(), is(0L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("missing")).findFirst().get().getCount()).isEqualTo(0L);
result = executionRepository.executionCounts( result = executionRepository.executionCounts(
null, null,
@@ -693,10 +693,10 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
null null
); );
assertThat(result.size(), is(3)); assertThat(result.size()).isEqualTo(3);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("first")).findFirst().get().getCount(), is(2L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("first")).findFirst().get().getCount()).isEqualTo(2L);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("second")).findFirst().get().getCount(), is(3L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("second")).findFirst().get().getCount()).isEqualTo(3L);
assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("third")).findFirst().get().getCount(), is(9L)); assertThat(result.stream().filter(executionCount -> executionCount.getFlowId().equals("third")).findFirst().get().getCount()).isEqualTo(9L);
result = executionRepository.executionCounts( result = executionRepository.executionCounts(
null, null,
@@ -706,8 +706,8 @@ public abstract class AbstractExecutionRepositoryTest {
null, null,
List.of(NAMESPACE) List.of(NAMESPACE)
); );
assertThat(result.size(), is(1)); assertThat(result.size()).isEqualTo(1);
assertThat(result.stream().filter(executionCount -> executionCount.getNamespace().equals(NAMESPACE)).findFirst().get().getCount(), is(14L)); assertThat(result.stream().filter(executionCount -> executionCount.getNamespace().equals(NAMESPACE)).findFirst().get().getCount()).isEqualTo(14L);
} }
@Test @Test
@@ -720,9 +720,9 @@ public abstract class AbstractExecutionRepositoryTest {
executionRepository.update(updated); executionRepository.update(updated);
Optional<Execution> validation = executionRepository.findById(null, updated.getId()); Optional<Execution> validation = executionRepository.findById(null, updated.getId());
assertThat(validation.isPresent(), is(true)); assertThat(validation.isPresent()).isEqualTo(true);
assertThat(validation.get().getLabels().size(), is(1)); assertThat(validation.get().getLabels().size()).isEqualTo(1);
assertThat(validation.get().getLabels().getFirst(), is(label)); assertThat(validation.get().getLabels().getFirst()).isEqualTo(label);
} }
@Test @Test
@@ -734,8 +734,8 @@ public abstract class AbstractExecutionRepositoryTest {
executionRepository.save(latest); executionRepository.save(latest);
Optional<Execution> result = executionRepository.findLatestForStates(null, "io.kestra.unittest", "full", List.of(State.Type.CREATED)); Optional<Execution> result = executionRepository.findLatestForStates(null, "io.kestra.unittest", "full", List.of(State.Type.CREATED));
assertThat(result.isPresent(), is(true)); assertThat(result.isPresent()).isEqualTo(true);
assertThat(result.get().getId(), is(latest.getId())); assertThat(result.get().getId()).isEqualTo(latest.getId());
} }
@Test @Test
@@ -766,11 +766,11 @@ public abstract class AbstractExecutionRepositoryTest {
null null
); );
assertThat(data.getTotal(), is(1L)); assertThat(data.getTotal()).isEqualTo(1L);
assertThat(data.get(0).get("count"), is(1L)); assertThat(data.get(0).get("count")).isEqualTo(1L);
assertThat(data.get(0).get("country"), is("FR")); assertThat(data.get(0).get("country")).isEqualTo("FR");
Instant startDate = execution.getState().getStartDate(); Instant startDate = execution.getState().getStartDate();
assertThat(data.get(0).get("date"), is(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(ZonedDateTime.ofInstant(startDate, ZoneId.systemDefault()).withSecond(0).withNano(0)))); assertThat(data.get(0).get("date")).isEqualTo(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(ZonedDateTime.ofInstant(startDate, ZoneId.systemDefault()).withSecond(0).withNano(0)));
} }
private static Execution buildWithCreatedDate(Instant instant) { private static Execution buildWithCreatedDate(Instant instant) {
@@ -790,6 +790,6 @@ public abstract class AbstractExecutionRepositoryTest {
inject(); inject();
List<Execution> executions = executionRepository.findAllAsync(null).collectList().block(); List<Execution> executions = executionRepository.findAllAsync(null).collectList().block();
assertThat(executions, hasSize(28)); assertThat(executions).hasSize(28);
} }
} }

View File

@@ -26,8 +26,7 @@ import java.time.ZonedDateTime;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractExecutionServiceTest { public abstract class AbstractExecutionServiceTest {
@@ -117,9 +116,9 @@ public abstract class AbstractExecutionServiceTest {
null null
); );
assertThat(purge.getExecutionsCount(), is(1)); assertThat(purge.getExecutionsCount()).isEqualTo(1);
assertThat(purge.getLogsCount(), is(10)); assertThat(purge.getLogsCount()).isEqualTo(10);
assertThat(purge.getStoragesCount(), is(5)); assertThat(purge.getStoragesCount()).isEqualTo(5);
purge = executionService.purge( purge = executionService.purge(
@@ -135,6 +134,6 @@ public abstract class AbstractExecutionServiceTest {
null null
); );
assertThat(purge.getExecutionsCount(), is(0)); assertThat(purge.getExecutionsCount()).isEqualTo(0);
} }
} }

View File

@@ -36,8 +36,7 @@ import java.util.*;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
@@ -83,11 +82,11 @@ public abstract class AbstractFlowRepositoryTest {
flow = flowRepository.create(GenericFlow.of(flow)); flow = flowRepository.create(GenericFlow.of(flow));
try { try {
Optional<Flow> full = flowRepository.findById(null, flow.getNamespace(), flow.getId()); Optional<Flow> full = flowRepository.findById(null, flow.getNamespace(), flow.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
assertThat(full.get().getRevision(), is(1)); assertThat(full.get().getRevision()).isEqualTo(1);
full = flowRepository.findById(null, flow.getNamespace(), flow.getId(), Optional.empty()); full = flowRepository.findById(null, flow.getNamespace(), flow.getId(), Optional.empty());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
} }
@@ -101,11 +100,11 @@ public abstract class AbstractFlowRepositoryTest {
flow = flowRepository.create(GenericFlow.of(flow)); flow = flowRepository.create(GenericFlow.of(flow));
try { try {
Optional<Flow> full = flowRepository.findByIdWithoutAcl(null, flow.getNamespace(), flow.getId(), Optional.empty()); Optional<Flow> full = flowRepository.findByIdWithoutAcl(null, flow.getNamespace(), flow.getId(), Optional.empty());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
assertThat(full.get().getRevision(), is(1)); assertThat(full.get().getRevision()).isEqualTo(1);
full = flowRepository.findByIdWithoutAcl(null, flow.getNamespace(), flow.getId(), Optional.empty()); full = flowRepository.findByIdWithoutAcl(null, flow.getNamespace(), flow.getId(), Optional.empty());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
} }
@@ -121,12 +120,12 @@ public abstract class AbstractFlowRepositoryTest {
try { try {
Optional<FlowWithSource> full = flowRepository.findByIdWithSource(null, flow.getNamespace(), flow.getId()); Optional<FlowWithSource> full = flowRepository.findByIdWithSource(null, flow.getNamespace(), flow.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
full.ifPresent(current -> { full.ifPresent(current -> {
assertThat(full.get().getRevision(), is(1)); assertThat(full.get().getRevision()).isEqualTo(1);
assertThat(full.get().getSource(), containsString("# comment")); assertThat(full.get().getSource()).contains("# comment");
assertThat(full.get().getSource(), not(containsString("revision:"))); assertThat(full.get().getSource()).doesNotContain("revision:");
}); });
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
@@ -139,7 +138,7 @@ public abstract class AbstractFlowRepositoryTest {
FlowWithSource save = flowRepository.create(GenericFlow.of(flow)); FlowWithSource save = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(save.getRevision(), is(1)); assertThat(save.getRevision()).isEqualTo(1);
} finally { } finally {
deleteFlow(save); deleteFlow(save);
} }
@@ -151,7 +150,7 @@ public abstract class AbstractFlowRepositoryTest {
FlowWithSource save = flowRepository.create(GenericFlow.of(flow)); FlowWithSource save = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(save.getRevision(), is(1)); assertThat(save.getRevision()).isEqualTo(1);
} finally { } finally {
deleteFlow(save); deleteFlow(save);
} }
@@ -162,52 +161,52 @@ public abstract class AbstractFlowRepositoryTest {
void findAll() { void findAll() {
List<Flow> save = flowRepository.findAll(null); List<Flow> save = flowRepository.findAll(null);
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
void findAllWithSource() { void findAllWithSource() {
List<FlowWithSource> save = flowRepository.findAllWithSource(null); List<FlowWithSource> save = flowRepository.findAllWithSource(null);
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
void findAllForAllTenants() { void findAllForAllTenants() {
List<Flow> save = flowRepository.findAllForAllTenants(); List<Flow> save = flowRepository.findAllForAllTenants();
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
void findAllWithSourceForAllTenants() { void findAllWithSourceForAllTenants() {
List<FlowWithSource> save = flowRepository.findAllWithSourceForAllTenants(); List<FlowWithSource> save = flowRepository.findAllWithSourceForAllTenants();
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
void findByNamespace() { void findByNamespace() {
List<Flow> save = flowRepository.findByNamespace(null, "io.kestra.tests"); List<Flow> save = flowRepository.findByNamespace(null, "io.kestra.tests");
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 20)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT - 20);
save = flowRepository.findByNamespace(null, "io.kestra.tests2"); save = flowRepository.findByNamespace(null, "io.kestra.tests2");
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
save = flowRepository.findByNamespace(null, "io.kestra.tests.minimal.bis"); save = flowRepository.findByNamespace(null, "io.kestra.tests.minimal.bis");
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
} }
@Test @Test
void findByNamespacePrefix() { void findByNamespacePrefix() {
List<Flow> save = flowRepository.findByNamespacePrefix(null, "io.kestra.tests"); List<Flow> save = flowRepository.findByNamespacePrefix(null, "io.kestra.tests");
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 1)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT - 1);
save = flowRepository.findByNamespace(null, "io.kestra.tests2"); save = flowRepository.findByNamespace(null, "io.kestra.tests2");
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
save = flowRepository.findByNamespace(null, "io.kestra.tests.minimal.bis"); save = flowRepository.findByNamespace(null, "io.kestra.tests.minimal.bis");
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
} }
@Test @Test
@@ -220,9 +219,9 @@ public abstract class AbstractFlowRepositoryTest {
try { try {
List<FlowWithSource> save = flowRepository.findByNamespaceWithSource(null, flow.getNamespace()); List<FlowWithSource> save = flowRepository.findByNamespaceWithSource(null, flow.getNamespace());
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
assertThat(save.getFirst().getSource(), is(FlowService.cleanupSource(flowSource))); assertThat(save.getFirst().getSource()).isEqualTo(FlowService.cleanupSource(flowSource));
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
} }
@@ -231,40 +230,40 @@ public abstract class AbstractFlowRepositoryTest {
@Test @Test
protected void find() { protected void find() {
List<Flow> save = flowRepository.find(Pageable.from(1, (int) Helpers.FLOWS_COUNT - 1, Sort.UNSORTED), null, null, null, null, null); List<Flow> save = flowRepository.find(Pageable.from(1, (int) Helpers.FLOWS_COUNT - 1, Sort.UNSORTED), null, null, null, null, null);
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 1)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT - 1);
save = flowRepository.find(Pageable.from(1, (int) Helpers.FLOWS_COUNT + 1, Sort.UNSORTED), null, null, null, null, null); save = flowRepository.find(Pageable.from(1, (int) Helpers.FLOWS_COUNT + 1, Sort.UNSORTED), null, null, null, null, null);
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT);
save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests.minimal.bis", Collections.emptyMap()); save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests.minimal.bis", Collections.emptyMap());
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
save = flowRepository.find(Pageable.from(1, 100, Sort.UNSORTED), null, null, null, null, Map.of("country", "FR")); save = flowRepository.find(Pageable.from(1, 100, Sort.UNSORTED), null, null, null, null, Map.of("country", "FR"));
assertThat(save.size(), is(1)); assertThat(save.size()).isEqualTo(1);
save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests", Map.of("key2", "value2")); save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests", Map.of("key2", "value2"));
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests", Map.of("key1", "value2")); save = flowRepository.find(Pageable.from(1), null, null, null, "io.kestra.tests", Map.of("key1", "value2"));
assertThat((long) save.size(), is(0L)); assertThat((long) save.size()).isEqualTo(0L);
} }
@Test @Test
protected void findSpecialChars() { protected void findSpecialChars() {
ArrayListTotal<SearchResult<Flow>> save = flowRepository.findSourceCode(Pageable.unpaged(), "https://api.chucknorris.io", null, null); ArrayListTotal<SearchResult<Flow>> save = flowRepository.findSourceCode(Pageable.unpaged(), "https://api.chucknorris.io", null, null);
assertThat((long) save.size(), is(2L)); assertThat((long) save.size()).isEqualTo(2L);
} }
@Test @Test
void findWithSource() { void findWithSource() {
List<FlowWithSource> save = flowRepository.findWithSource(null, null, null, "io.kestra.tests", Collections.emptyMap()); List<FlowWithSource> save = flowRepository.findWithSource(null, null, null, "io.kestra.tests", Collections.emptyMap());
assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 1)); assertThat((long) save.size()).isEqualTo(Helpers.FLOWS_COUNT - 1);
save = flowRepository.findWithSource(null, null, null, "io.kestra.tests2", Collections.emptyMap()); save = flowRepository.findWithSource(null, null, null, "io.kestra.tests2", Collections.emptyMap());
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
save = flowRepository.findWithSource(null, null, null, "io.kestra.tests.minimal.bis", Collections.emptyMap()); save = flowRepository.findWithSource(null, null, null, "io.kestra.tests.minimal.bis", Collections.emptyMap());
assertThat((long) save.size(), is(1L)); assertThat((long) save.size()).isEqualTo(1L);
} }
@Test @Test
@@ -274,7 +273,7 @@ public abstract class AbstractFlowRepositoryTest {
FlowWithSource save = flowRepository.create(GenericFlow.of(flow)); FlowWithSource save = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(flowRepository.findById(null, save.getNamespace(), save.getId()).isPresent(), is(true)); assertThat(flowRepository.findById(null, save.getNamespace(), save.getId()).isPresent()).isEqualTo(true);
} catch (Throwable e) { } catch (Throwable e) {
deleteFlow(save); deleteFlow(save);
throw e; throw e;
@@ -282,11 +281,11 @@ public abstract class AbstractFlowRepositoryTest {
Flow delete = flowRepository.delete(save); Flow delete = flowRepository.delete(save);
assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent(), is(false)); assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent()).isEqualTo(false);
assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId(), Optional.of(save.getRevision())).isPresent(), is(true)); assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId(), Optional.of(save.getRevision())).isPresent()).isEqualTo(true);
List<FlowWithSource> revisions = flowRepository.findRevisions(null, flow.getNamespace(), flow.getId()); List<FlowWithSource> revisions = flowRepository.findRevisions(null, flow.getNamespace(), flow.getId());
assertThat(revisions.getLast().getRevision(), is(delete.getRevision())); assertThat(revisions.getLast().getRevision()).isEqualTo(delete.getRevision());
} }
@Test @Test
@@ -303,7 +302,7 @@ public abstract class AbstractFlowRepositoryTest {
Flow save = flowRepository.create(GenericFlow.of(flow)); Flow save = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent(), is(true)); assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent()).isEqualTo(true);
Flow update = Flow.builder() Flow update = Flow.builder()
.id(IdUtils.create()) .id(IdUtils.create())
@@ -318,7 +317,7 @@ public abstract class AbstractFlowRepositoryTest {
() -> flowRepository.update(GenericFlow.of(update), flow) () -> flowRepository.update(GenericFlow.of(update), flow)
); );
assertThat(e.getConstraintViolations().size(), is(2)); assertThat(e.getConstraintViolations().size()).isEqualTo(2);
} finally { } finally {
deleteFlow(save); deleteFlow(save);
} }
@@ -340,7 +339,7 @@ public abstract class AbstractFlowRepositoryTest {
flow = flowRepository.create(GenericFlow.of(flow)); flow = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent(), is(true)); assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent()).isEqualTo(true);
Flow update = Flow.builder() Flow update = Flow.builder()
.id(flowId) .id(flowId)
@@ -350,15 +349,15 @@ public abstract class AbstractFlowRepositoryTest {
; ;
Flow updated = flowRepository.update(GenericFlow.of(update), flow); Flow updated = flowRepository.update(GenericFlow.of(update), flow);
assertThat(updated.getTriggers(), is(nullValue())); assertThat(updated.getTriggers()).isNull();
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
} }
Await.until(() -> FlowListener.getEmits().size() == 3, Duration.ofMillis(100), Duration.ofSeconds(5)); Await.until(() -> FlowListener.getEmits().size() == 3, Duration.ofMillis(100), Duration.ofSeconds(5));
assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count(), is(1L)); assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count()).isEqualTo(1L);
assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.UPDATE).count(), is(1L)); assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.UPDATE).count()).isEqualTo(1L);
assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count(), is(1L)); assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count()).isEqualTo(1L);
} }
@@ -378,20 +377,20 @@ public abstract class AbstractFlowRepositoryTest {
Flow save = flowRepository.create(GenericFlow.of(flow)); Flow save = flowRepository.create(GenericFlow.of(flow));
try { try {
assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent(), is(true)); assertThat(flowRepository.findById(null, flow.getNamespace(), flow.getId()).isPresent()).isEqualTo(true);
} finally { } finally {
deleteFlow(save); deleteFlow(save);
} }
Await.until(() -> FlowListener.getEmits().size() == 2, Duration.ofMillis(100), Duration.ofSeconds(5)); Await.until(() -> FlowListener.getEmits().size() == 2, Duration.ofMillis(100), Duration.ofSeconds(5));
assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count(), is(1L)); assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count()).isEqualTo(1L);
assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count(), is(1L)); assertThat(FlowListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count()).isEqualTo(1L);
} }
@Test @Test
void findDistinctNamespace() { void findDistinctNamespace() {
List<String> distinctNamespace = flowRepository.findDistinctNamespace(null); List<String> distinctNamespace = flowRepository.findDistinctNamespace(null);
assertThat((long) distinctNamespace.size(), is(7L)); assertThat((long) distinctNamespace.size()).isEqualTo(7L);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -421,9 +420,9 @@ public abstract class AbstractFlowRepositoryTest {
try { try {
Optional<Flow> found = flowRepository.findById(null, flow.getNamespace(), flow.getId()); Optional<Flow> found = flowRepository.findById(null, flow.getNamespace(), flow.getId());
assertThat(found.isPresent(), is(true)); assertThat(found.isPresent()).isEqualTo(true);
assertThat(found.get() instanceof FlowWithException, is(true)); assertThat(found.get() instanceof FlowWithException).isEqualTo(true);
assertThat(((FlowWithException) found.get()).getException(), containsString("Templates are disabled")); assertThat(((FlowWithException) found.get()).getException()).contains("Templates are disabled");
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
} }
@@ -431,7 +430,7 @@ public abstract class AbstractFlowRepositoryTest {
@Test @Test
protected void shouldReturnNullRevisionForNonExistingFlow() { protected void shouldReturnNullRevisionForNonExistingFlow() {
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, IdUtils.create()), nullValue()); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, IdUtils.create())).isNull();
} }
@Test @Test
@@ -445,8 +444,8 @@ public abstract class AbstractFlowRepositoryTest {
Integer result = flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId); Integer result = flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId);
// Then // Then
assertThat(result, is(1)); assertThat(result).isEqualTo(1);
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId), is(1)); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId)).isEqualTo(1);
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
} }
@@ -457,13 +456,13 @@ public abstract class AbstractFlowRepositoryTest {
// Given // Given
final String flowId = IdUtils.create(); final String flowId = IdUtils.create();
FlowWithSource created = flowRepository.create(createTestingLogFlow(flowId, "first")); FlowWithSource created = flowRepository.create(createTestingLogFlow(flowId, "first"));
assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size(), is(1)); assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size()).isEqualTo(1);
// When // When
flowRepository.delete(created); flowRepository.delete(created);
// Then // Then
assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size(), is(2)); assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size()).isEqualTo(2);
} }
@Test @Test
@@ -481,8 +480,8 @@ public abstract class AbstractFlowRepositoryTest {
toDelete.add(flowRepository.create(createTestingLogFlow(flowId, "second"))); toDelete.add(flowRepository.create(createTestingLogFlow(flowId, "second")));
// Then // Then
assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size(), is(3)); assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size()).isEqualTo(3);
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId), is(3)); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId)).isEqualTo(3);
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
} }
@@ -505,8 +504,8 @@ public abstract class AbstractFlowRepositoryTest {
flowRepository.delete(updated); flowRepository.delete(updated);
// Then // Then
assertThat(flowRepository.findById(TEST_TENANT_ID, TEST_NAMESPACE, flowId, Optional.empty()), is(Optional.empty())); assertThat(flowRepository.findById(TEST_TENANT_ID, TEST_NAMESPACE, flowId, Optional.empty())).isEqualTo(Optional.empty());
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId), is(nullValue())); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId)).isNull();
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
} }
@@ -529,8 +528,8 @@ public abstract class AbstractFlowRepositoryTest {
flowRepository.delete(updated); flowRepository.delete(updated);
// Then // Then
assertThat(flowRepository.findById(TEST_TENANT_ID, TEST_NAMESPACE, flowId, Optional.empty()), is(Optional.empty())); assertThat(flowRepository.findById(TEST_TENANT_ID, TEST_NAMESPACE, flowId, Optional.empty())).isEqualTo(Optional.empty());
assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size(), is(3)); assertThat(flowRepository.findRevisions(TEST_TENANT_ID, TEST_NAMESPACE, flowId).size()).isEqualTo(3);
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
} }
@@ -551,8 +550,8 @@ public abstract class AbstractFlowRepositoryTest {
toDelete.add(updated); toDelete.add(updated);
// Then // Then
assertThat(updated.getRevision(), is(2)); assertThat(updated.getRevision()).isEqualTo(2);
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId), is(2)); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId)).isEqualTo(2);
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
@@ -574,8 +573,8 @@ public abstract class AbstractFlowRepositoryTest {
toDelete.add(updated); toDelete.add(updated);
// Then // Then
assertThat(updated.getRevision(), is(1)); assertThat(updated.getRevision()).isEqualTo(1);
assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId), is(1)); assertThat(flowRepository.lastRevision(TEST_TENANT_ID, TEST_NAMESPACE, flowId)).isEqualTo(1);
} finally { } finally {
toDelete.forEach(this::deleteFlow); toDelete.forEach(this::deleteFlow);
@@ -585,8 +584,8 @@ public abstract class AbstractFlowRepositoryTest {
@Test @Test
void shouldReturnForFindGivenQueryWildcard() { void shouldReturnForFindGivenQueryWildcard() {
ArrayListTotal<Flow> flows = flowRepository.find(Pageable.from(1, 10), "*", null, null, null, Map.of()); ArrayListTotal<Flow> flows = flowRepository.find(Pageable.from(1, 10), "*", null, null, null, Map.of());
assertThat(flows.size(), is(10)); assertThat(flows.size()).isEqualTo(10);
assertThat(flows.getTotal(), is(Helpers.FLOWS_COUNT)); assertThat(flows.getTotal()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
@@ -595,8 +594,8 @@ public abstract class AbstractFlowRepositoryTest {
QueryFilter.builder().field(QueryFilter.Field.QUERY).operation(QueryFilter.Op.EQUALS).value("*").build() QueryFilter.builder().field(QueryFilter.Field.QUERY).operation(QueryFilter.Op.EQUALS).value("*").build()
); );
ArrayListTotal<Flow> flows = flowRepository.find(Pageable.from(1, 10), null, filters); ArrayListTotal<Flow> flows = flowRepository.find(Pageable.from(1, 10), null, filters);
assertThat(flows.size(), is(10)); assertThat(flows.size()).isEqualTo(10);
assertThat(flows.getTotal(), is(Helpers.FLOWS_COUNT)); assertThat(flows.getTotal()).isEqualTo(Helpers.FLOWS_COUNT);
} }
@Test @Test
@@ -616,14 +615,14 @@ public abstract class AbstractFlowRepositoryTest {
try { try {
Flow full = flowRepository.findByExecution(execution); Flow full = flowRepository.findByExecution(execution);
assertThat(full, notNullValue()); assertThat(full).isNotNull();
assertThat(full.getNamespace(), is(flow.getNamespace())); assertThat(full.getNamespace()).isEqualTo(flow.getNamespace());
assertThat(full.getId(), is(flow.getId())); assertThat(full.getId()).isEqualTo(flow.getId());
full = flowRepository.findByExecutionWithoutAcl(execution); full = flowRepository.findByExecutionWithoutAcl(execution);
assertThat(full, notNullValue()); assertThat(full).isNotNull();
assertThat(full.getNamespace(), is(flow.getNamespace())); assertThat(full.getNamespace()).isEqualTo(flow.getNamespace());
assertThat(full.getId(), is(flow.getId())); assertThat(full.getId()).isEqualTo(flow.getId());
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
executionRepository.delete(execution); executionRepository.delete(execution);
@@ -646,14 +645,14 @@ public abstract class AbstractFlowRepositoryTest {
try { try {
Flow full = flowRepository.findByExecution(execution); Flow full = flowRepository.findByExecution(execution);
assertThat(full, notNullValue()); assertThat(full).isNotNull();
assertThat(full.getNamespace(), is(flow.getNamespace())); assertThat(full.getNamespace()).isEqualTo(flow.getNamespace());
assertThat(full.getId(), is(flow.getId())); assertThat(full.getId()).isEqualTo(flow.getId());
full = flowRepository.findByExecutionWithoutAcl(execution); full = flowRepository.findByExecutionWithoutAcl(execution);
assertThat(full, notNullValue()); assertThat(full).isNotNull();
assertThat(full.getNamespace(), is(flow.getNamespace())); assertThat(full.getNamespace()).isEqualTo(flow.getNamespace());
assertThat(full.getId(), is(flow.getId())); assertThat(full.getId()).isEqualTo(flow.getId());
} finally { } finally {
deleteFlow(flow); deleteFlow(flow);
executionRepository.delete(execution); executionRepository.delete(execution);
@@ -688,10 +687,10 @@ public abstract class AbstractFlowRepositoryTest {
toDelete.add(flowRepository.create(GenericFlow.of(createTestFlowForNamespace("com.kestra.unittest")))); toDelete.add(flowRepository.create(GenericFlow.of(createTestFlowForNamespace("com.kestra.unittest"))));
int count = flowRepository.countForNamespace(null, "io.kestra.unittest.shouldcountbynamespacefornulltenant"); int count = flowRepository.countForNamespace(null, "io.kestra.unittest.shouldcountbynamespacefornulltenant");
assertThat(count, is(1)); assertThat(count).isEqualTo(1);
count = flowRepository.countForNamespace(null, TEST_NAMESPACE); count = flowRepository.countForNamespace(null, TEST_NAMESPACE);
assertThat(count, is(2)); assertThat(count).isEqualTo(2);
} finally { } finally {
for (FlowWithSource flow : toDelete) { for (FlowWithSource flow : toDelete) {
flowRepository.delete(flow); flowRepository.delete(flow);

View File

@@ -9,8 +9,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractFlowTopologyRepositoryTest { public abstract class AbstractFlowTopologyRepositoryTest {
@@ -43,6 +42,6 @@ public abstract class AbstractFlowTopologyRepositoryTest {
List<FlowTopology> list = flowTopologyRepository.findByFlow(null, "io.kestra.tests", "flow-a", false); List<FlowTopology> list = flowTopologyRepository.findByFlow(null, "io.kestra.tests", "flow-a", false);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
} }
} }

View File

@@ -18,9 +18,7 @@ import java.time.ZonedDateTime;
import java.util.List; import java.util.List;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractLogRepositoryTest { public abstract class AbstractLogRepositoryTest {
@@ -46,14 +44,14 @@ public abstract class AbstractLogRepositoryTest {
LogEntry.LogEntryBuilder builder = logEntry(Level.INFO); LogEntry.LogEntryBuilder builder = logEntry(Level.INFO);
ArrayListTotal<LogEntry> find = logRepository.find(Pageable.UNPAGED, null, null); ArrayListTotal<LogEntry> find = logRepository.find(Pageable.UNPAGED, null, null);
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
LogEntry save = logRepository.save(builder.build()); LogEntry save = logRepository.save(builder.build());
find = logRepository.find(Pageable.UNPAGED, null, null); find = logRepository.find(Pageable.UNPAGED, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(find.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
var filters = List.of(QueryFilter.builder() var filters = List.of(QueryFilter.builder()
.field(QueryFilter.Field.MIN_LEVEL) .field(QueryFilter.Field.MIN_LEVEL)
.operation(QueryFilter.Op.EQUALS) .operation(QueryFilter.Op.EQUALS)
@@ -65,45 +63,45 @@ public abstract class AbstractLogRepositoryTest {
.value(Instant.now().minus(1, ChronoUnit.HOURS)) .value(Instant.now().minus(1, ChronoUnit.HOURS))
.build()); .build());
find = logRepository.find(Pageable.UNPAGED, "doe", filters); find = logRepository.find(Pageable.UNPAGED, "doe", filters);
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
find = logRepository.find(Pageable.UNPAGED, null, null); find = logRepository.find(Pageable.UNPAGED, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(find.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
logRepository.find(Pageable.UNPAGED, "kestra-io/kestra", null); logRepository.find(Pageable.UNPAGED, "kestra-io/kestra", null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(find.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
List<LogEntry> list = logRepository.findByExecutionId(null, save.getExecutionId(), null); List<LogEntry> list = logRepository.findByExecutionId(null, save.getExecutionId(), null);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
list = logRepository.findByExecutionId(null, "io.kestra.unittest", "flowId", save.getExecutionId(), null); list = logRepository.findByExecutionId(null, "io.kestra.unittest", "flowId", save.getExecutionId(), null);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
list = logRepository.findByExecutionIdAndTaskId(null, save.getExecutionId(), save.getTaskId(), null); list = logRepository.findByExecutionIdAndTaskId(null, save.getExecutionId(), save.getTaskId(), null);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
list = logRepository.findByExecutionIdAndTaskId(null, "io.kestra.unittest", "flowId", save.getExecutionId(), save.getTaskId(), null); list = logRepository.findByExecutionIdAndTaskId(null, "io.kestra.unittest", "flowId", save.getExecutionId(), save.getTaskId(), null);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
list = logRepository.findByExecutionIdAndTaskRunId(null, save.getExecutionId(), save.getTaskRunId(), null); list = logRepository.findByExecutionIdAndTaskRunId(null, save.getExecutionId(), save.getTaskRunId(), null);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
list = logRepository.findByExecutionIdAndTaskRunIdAndAttempt(null, save.getExecutionId(), save.getTaskRunId(), null, 0); list = logRepository.findByExecutionIdAndTaskRunIdAndAttempt(null, save.getExecutionId(), save.getTaskRunId(), null, 0);
assertThat(list.size(), is(1)); assertThat(list.size()).isEqualTo(1);
assertThat(list.getFirst().getExecutionId(), is(save.getExecutionId())); assertThat(list.getFirst().getExecutionId()).isEqualTo(save.getExecutionId());
Integer countDeleted = logRepository.purge(Execution.builder().id(save.getExecutionId()).build()); Integer countDeleted = logRepository.purge(Execution.builder().id(save.getExecutionId()).build());
assertThat(countDeleted, is(1)); assertThat(countDeleted).isEqualTo(1);
list = logRepository.findByExecutionIdAndTaskId(null, save.getExecutionId(), save.getTaskId(), null); list = logRepository.findByExecutionIdAndTaskId(null, save.getExecutionId(), save.getTaskId(), null);
assertThat(list.size(), is(0)); assertThat(list.size()).isEqualTo(0);
} }
@Test @Test
@@ -124,32 +122,32 @@ public abstract class AbstractLogRepositoryTest {
ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, executionId, null, Pageable.from(1, 50)); ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, executionId, null, Pageable.from(1, 50));
assertThat(find.size(), is(50)); assertThat(find.size()).isEqualTo(50);
assertThat(find.getTotal(), is(101L)); assertThat(find.getTotal()).isEqualTo(101L);
find = logRepository.findByExecutionId(null, executionId, null, Pageable.from(3, 50)); find = logRepository.findByExecutionId(null, executionId, null, Pageable.from(3, 50));
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getTotal(), is(101L)); assertThat(find.getTotal()).isEqualTo(101L);
find = logRepository.findByExecutionIdAndTaskId(null, executionId, logEntry2.getTaskId(), null, Pageable.from(1, 50)); find = logRepository.findByExecutionIdAndTaskId(null, executionId, logEntry2.getTaskId(), null, Pageable.from(1, 50));
assertThat(find.size(), is(21)); assertThat(find.size()).isEqualTo(21);
assertThat(find.getTotal(), is(21L)); assertThat(find.getTotal()).isEqualTo(21L);
find = logRepository.findByExecutionIdAndTaskRunId(null, executionId, logEntry2.getTaskRunId(), null, Pageable.from(1, 10)); find = logRepository.findByExecutionIdAndTaskRunId(null, executionId, logEntry2.getTaskRunId(), null, Pageable.from(1, 10));
assertThat(find.size(), is(10)); assertThat(find.size()).isEqualTo(10);
assertThat(find.getTotal(), is(21L)); assertThat(find.getTotal()).isEqualTo(21L);
find = logRepository.findByExecutionIdAndTaskRunIdAndAttempt(null, executionId, logEntry2.getTaskRunId(), null, 0, Pageable.from(1, 10)); find = logRepository.findByExecutionIdAndTaskRunIdAndAttempt(null, executionId, logEntry2.getTaskRunId(), null, 0, Pageable.from(1, 10));
assertThat(find.size(), is(10)); assertThat(find.size()).isEqualTo(10);
assertThat(find.getTotal(), is(21L)); assertThat(find.getTotal()).isEqualTo(21L);
find = logRepository.findByExecutionIdAndTaskRunId(null, executionId, logEntry2.getTaskRunId(), null, Pageable.from(10, 10)); find = logRepository.findByExecutionIdAndTaskRunId(null, executionId, logEntry2.getTaskRunId(), null, Pageable.from(10, 10));
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
} }
@Test @Test
@@ -160,14 +158,14 @@ public abstract class AbstractLogRepositoryTest {
logRepository.deleteByQuery(null, log1.getExecutionId(), null, (String) null, null, null); logRepository.deleteByQuery(null, log1.getExecutionId(), null, (String) null, null, null);
ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50)); ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50));
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
logRepository.save(log1); logRepository.save(log1);
logRepository.deleteByQuery(null, "io.kestra.unittest", "flowId", List.of(Level.TRACE, Level.DEBUG, Level.INFO), null, ZonedDateTime.now().plusMinutes(1)); logRepository.deleteByQuery(null, "io.kestra.unittest", "flowId", List.of(Level.TRACE, Level.DEBUG, Level.INFO), null, ZonedDateTime.now().plusMinutes(1));
find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50)); find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50));
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
} }
@Test @Test
@@ -178,14 +176,14 @@ public abstract class AbstractLogRepositoryTest {
logRepository.deleteByQuery(null, log1.getExecutionId(), null, (String) null, null, null); logRepository.deleteByQuery(null, log1.getExecutionId(), null, (String) null, null, null);
ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50)); ArrayListTotal<LogEntry> find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50));
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
logRepository.save(log1); logRepository.save(log1);
logRepository.deleteByQuery(null, "io.kestra.unittest", "flowId", null); logRepository.deleteByQuery(null, "io.kestra.unittest", "flowId", null);
find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50)); find = logRepository.findByExecutionId(null, log1.getExecutionId(), null, Pageable.from(1, 50));
assertThat(find.size(), is(0)); assertThat(find.size()).isEqualTo(0);
} }
@Test @Test
@@ -202,14 +200,14 @@ public abstract class AbstractLogRepositoryTest {
Thread.sleep(500); Thread.sleep(500);
List<LogStatistics> list = logRepository.statistics(null, null, null, "first", null, null, null, null); List<LogStatistics> list = logRepository.statistics(null, null, null, "first", null, null, null, null);
assertThat(list.size(), is(31)); assertThat(list.size()).isEqualTo(31);
assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.TRACE) == 5).count(), is(1L)); assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.TRACE) == 5).count()).isEqualTo(1L);
assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.INFO) == 3).count(), is(1L)); assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.INFO) == 3).count()).isEqualTo(1L);
assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.ERROR) == 7).count(), is(1L)); assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.ERROR) == 7).count()).isEqualTo(1L);
list = logRepository.statistics(null, null, null, "second", null, null, null, null); list = logRepository.statistics(null, null, null, "second", null, null, null, null);
assertThat(list.size(), is(31)); assertThat(list.size()).isEqualTo(31);
assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.ERROR) == 13).count(), is(1L)); assertThat(list.stream().filter(logStatistics -> logStatistics.getCounts().get(Level.ERROR) == 13).count()).isEqualTo(1L);
} }
@Test @Test
@@ -222,19 +220,19 @@ public abstract class AbstractLogRepositoryTest {
Flux<LogEntry> find = logRepository.findAsync(null, "io.kestra.unittest", Level.INFO, startDate); Flux<LogEntry> find = logRepository.findAsync(null, "io.kestra.unittest", Level.INFO, startDate);
List<LogEntry> logEntries = find.collectList().block(); List<LogEntry> logEntries = find.collectList().block();
assertThat(logEntries, hasSize(3)); assertThat(logEntries).hasSize(3);
find = logRepository.findAsync(null, null, Level.ERROR, startDate); find = logRepository.findAsync(null, null, Level.ERROR, startDate);
logEntries = find.collectList().block(); logEntries = find.collectList().block();
assertThat(logEntries, hasSize(1)); assertThat(logEntries).hasSize(1);
find = logRepository.findAsync(null, "io.kestra.unused", Level.INFO, startDate); find = logRepository.findAsync(null, "io.kestra.unused", Level.INFO, startDate);
logEntries = find.collectList().block(); logEntries = find.collectList().block();
assertThat(logEntries, hasSize(0)); assertThat(logEntries).hasSize(0);
find = logRepository.findAsync(null, null, Level.INFO, startDate.plusSeconds(2)); find = logRepository.findAsync(null, null, Level.INFO, startDate.plusSeconds(2));
logEntries = find.collectList().block(); logEntries = find.collectList().block();
assertThat(logEntries, hasSize(0)); assertThat(logEntries).hasSize(0);
} }
@Test @Test
@@ -245,6 +243,6 @@ public abstract class AbstractLogRepositoryTest {
Flux<LogEntry> find = logRepository.findAllAsync(null); Flux<LogEntry> find = logRepository.findAllAsync(null);
List<LogEntry> logEntries = find.collectList().block(); List<LogEntry> logEntries = find.collectList().block();
assertThat(logEntries, hasSize(3)); assertThat(logEntries).hasSize(3);
} }
} }

View File

@@ -15,9 +15,7 @@ import java.time.Duration;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractMetricRepositoryTest { public abstract class AbstractMetricRepositoryTest {
@@ -35,13 +33,13 @@ public abstract class AbstractMetricRepositoryTest {
metricRepository.save(timer); metricRepository.save(timer);
List<MetricEntry> results = metricRepository.findByExecutionId(null, executionId, Pageable.from(1, 10)); List<MetricEntry> results = metricRepository.findByExecutionId(null, executionId, Pageable.from(1, 10));
assertThat(results.size(), is(2)); assertThat(results.size()).isEqualTo(2);
results = metricRepository.findByExecutionIdAndTaskId(null, executionId, taskRun1.getTaskId(), Pageable.from(1, 10)); results = metricRepository.findByExecutionIdAndTaskId(null, executionId, taskRun1.getTaskId(), Pageable.from(1, 10));
assertThat(results.size(), is(2)); assertThat(results.size()).isEqualTo(2);
results = metricRepository.findByExecutionIdAndTaskRunId(null, executionId, taskRun1.getId(), Pageable.from(1, 10)); results = metricRepository.findByExecutionIdAndTaskRunId(null, executionId, taskRun1.getId(), Pageable.from(1, 10));
assertThat(results.size(), is(1)); assertThat(results.size()).isEqualTo(1);
MetricAggregations aggregationResults = metricRepository.aggregateByFlowId( MetricAggregations aggregationResults = metricRepository.aggregateByFlowId(
null, null,
@@ -54,8 +52,8 @@ public abstract class AbstractMetricRepositoryTest {
"sum" "sum"
); );
assertThat(aggregationResults.getAggregations().size(), is(31)); assertThat(aggregationResults.getAggregations().size()).isEqualTo(31);
assertThat(aggregationResults.getGroupBy(), is("day")); assertThat(aggregationResults.getGroupBy()).isEqualTo("day");
aggregationResults = metricRepository.aggregateByFlowId( aggregationResults = metricRepository.aggregateByFlowId(
null, null,
@@ -68,8 +66,8 @@ public abstract class AbstractMetricRepositoryTest {
"sum" "sum"
); );
assertThat(aggregationResults.getAggregations().size(), is(27)); assertThat(aggregationResults.getAggregations().size()).isEqualTo(27);
assertThat(aggregationResults.getGroupBy(), is("week")); assertThat(aggregationResults.getGroupBy()).isEqualTo("week");
} }
@@ -90,9 +88,9 @@ public abstract class AbstractMetricRepositoryTest {
List<String> taskMetricsNames = metricRepository.taskMetrics(null, "namespace", "flow", "task"); List<String> taskMetricsNames = metricRepository.taskMetrics(null, "namespace", "flow", "task");
List<String> tasksWithMetrics = metricRepository.tasksWithMetrics(null, "namespace", "flow"); List<String> tasksWithMetrics = metricRepository.tasksWithMetrics(null, "namespace", "flow");
assertThat(flowMetricsNames.size(), is(2)); assertThat(flowMetricsNames.size()).isEqualTo(2);
assertThat(taskMetricsNames.size(), is(1)); assertThat(taskMetricsNames.size()).isEqualTo(1);
assertThat(tasksWithMetrics.size(), is(2)); assertThat(tasksWithMetrics.size()).isEqualTo(2);
} }
@Test @Test
@@ -106,7 +104,7 @@ public abstract class AbstractMetricRepositoryTest {
metricRepository.save(timer); metricRepository.save(timer);
List<MetricEntry> results = metricRepository.findAllAsync(null).collectList().block(); List<MetricEntry> results = metricRepository.findAllAsync(null).collectList().block();
assertThat(results, hasSize(2)); assertThat(results).hasSize(2);
} }
private Counter counter(String metricName) { private Counter counter(String metricName) {

View File

@@ -9,8 +9,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractSettingRepositoryTest { public abstract class AbstractSettingRepositoryTest {
@@ -25,26 +24,26 @@ public abstract class AbstractSettingRepositoryTest {
.build(); .build();
Optional<Setting> find = settingRepository.findByKey(setting.getKey()); Optional<Setting> find = settingRepository.findByKey(setting.getKey());
assertThat(find.isPresent(), is(false)); assertThat(find.isPresent()).isEqualTo(false);
Setting save = settingRepository.save(setting); Setting save = settingRepository.save(setting);
find = settingRepository.findByKey(save.getKey()); find = settingRepository.findByKey(save.getKey());
assertThat(find.isPresent(), is(true)); assertThat(find.isPresent()).isEqualTo(true);
assertThat(find.get().getValue(), is(save.getValue())); assertThat(find.get().getValue()).isEqualTo(save.getValue());
List<Setting> all = settingRepository.findAll(); List<Setting> all = settingRepository.findAll();
assertThat(all.size(), is(1)); assertThat(all.size()).isEqualTo(1);
assertThat(all.getFirst().getValue(), is(setting.getValue())); assertThat(all.getFirst().getValue()).isEqualTo(setting.getValue());
Setting delete = settingRepository.delete(setting); Setting delete = settingRepository.delete(setting);
assertThat(delete.getValue(), is(setting.getValue())); assertThat(delete.getValue()).isEqualTo(setting.getValue());
all = settingRepository.findAll(); all = settingRepository.findAll();
assertThat(all.size(), is(0)); assertThat(all.size()).isEqualTo(0);
find = settingRepository.findByKey(setting.getKey()); find = settingRepository.findByKey(setting.getKey());
assertThat(find.isPresent(), is(false)); assertThat(find.isPresent()).isEqualTo(false);
} }
} }

View File

@@ -21,8 +21,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
public abstract class AbstractTemplateRepositoryTest { public abstract class AbstractTemplateRepositoryTest {
@@ -51,12 +50,12 @@ public abstract class AbstractTemplateRepositoryTest {
templateRepository.create(template); templateRepository.create(template);
Optional<Template> full = templateRepository.findById(null, template.getNamespace(), template.getId()); Optional<Template> full = templateRepository.findById(null, template.getNamespace(), template.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
assertThat(full.get().getId(), is(template.getId())); assertThat(full.get().getId()).isEqualTo(template.getId());
full = templateRepository.findById(null, template.getNamespace(), template.getId()); full = templateRepository.findById(null, template.getNamespace(), template.getId());
assertThat(full.isPresent(), is(true)); assertThat(full.isPresent()).isEqualTo(true);
assertThat(full.get().getId(), is(template.getId())); assertThat(full.get().getId()).isEqualTo(template.getId());
} }
@Test @Test
@@ -70,9 +69,9 @@ public abstract class AbstractTemplateRepositoryTest {
templateRepository.create(template2); templateRepository.create(template2);
List<Template> templates = templateRepository.findByNamespace(null, template1.getNamespace()); List<Template> templates = templateRepository.findByNamespace(null, template1.getNamespace());
assertThat(templates.size(), greaterThanOrEqualTo(1)); assertThat(templates.size()).isGreaterThanOrEqualTo(1);
templates = templateRepository.findByNamespace(null, template2.getNamespace()); templates = templateRepository.findByNamespace(null, template2.getNamespace());
assertThat(templates.size(), is(1)); assertThat(templates.size()).isEqualTo(1);
} }
@Test @Test
@@ -80,7 +79,7 @@ public abstract class AbstractTemplateRepositoryTest {
Template template = builder().build(); Template template = builder().build();
Template save = templateRepository.create(template); Template save = templateRepository.create(template);
assertThat(save.getId(), is(template.getId())); assertThat(save.getId()).isEqualTo(template.getId());
} }
@Test @Test
@@ -89,9 +88,9 @@ public abstract class AbstractTemplateRepositoryTest {
Template template = builder().build(); Template template = builder().build();
templateRepository.create(template); templateRepository.create(template);
long size = templateRepository.findAll(null).size(); long size = templateRepository.findAll(null).size();
assertThat(size, greaterThan(saveCount)); assertThat(size).isGreaterThan(saveCount);
templateRepository.delete(template); templateRepository.delete(template);
assertThat((long) templateRepository.findAll(null).size(), is(saveCount)); assertThat((long) templateRepository.findAll(null).size()).isEqualTo(saveCount);
} }
@Test @Test
@@ -100,9 +99,9 @@ public abstract class AbstractTemplateRepositoryTest {
Template template = builder().build(); Template template = builder().build();
templateRepository.create(template); templateRepository.create(template);
long size = templateRepository.findAllForAllTenants().size(); long size = templateRepository.findAllForAllTenants().size();
assertThat(size, greaterThan(saveCount)); assertThat(size).isGreaterThan(saveCount);
templateRepository.delete(template); templateRepository.delete(template);
assertThat((long) templateRepository.findAllForAllTenants().size(), is(saveCount)); assertThat((long) templateRepository.findAllForAllTenants().size()).isEqualTo(saveCount);
} }
@Test @Test
@@ -116,11 +115,11 @@ public abstract class AbstractTemplateRepositoryTest {
// with pageable // with pageable
List<Template> save = templateRepository.find(Pageable.from(1, 10),null, null, "kestra.test"); List<Template> save = templateRepository.find(Pageable.from(1, 10),null, null, "kestra.test");
assertThat((long) save.size(), greaterThanOrEqualTo(3L)); assertThat((long) save.size()).isGreaterThanOrEqualTo(3L);
// without pageable // without pageable
save = templateRepository.find(null, null, "kestra.test"); save = templateRepository.find(null, null, "kestra.test");
assertThat((long) save.size(), greaterThanOrEqualTo(3L)); assertThat((long) save.size()).isGreaterThanOrEqualTo(3L);
templateRepository.delete(template1); templateRepository.delete(template1);
templateRepository.delete(template2); templateRepository.delete(template2);
@@ -134,11 +133,11 @@ public abstract class AbstractTemplateRepositoryTest {
Template save = templateRepository.create(template); Template save = templateRepository.create(template);
templateRepository.delete(save); templateRepository.delete(save);
assertThat(templateRepository.findById(null, template.getNamespace(), template.getId()).isPresent(), is(false)); assertThat(templateRepository.findById(null, template.getNamespace(), template.getId()).isPresent()).isEqualTo(false);
assertThat(TemplateListener.getEmits().size(), is(2)); assertThat(TemplateListener.getEmits().size()).isEqualTo(2);
assertThat(TemplateListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count(), is(1L)); assertThat(TemplateListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.CREATE).count()).isEqualTo(1L);
assertThat(TemplateListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count(), is(1L)); assertThat(TemplateListener.getEmits().stream().filter(r -> r.getType() == CrudEventType.DELETE).count()).isEqualTo(1L);
} }
@Singleton @Singleton

View File

@@ -12,8 +12,7 @@ import java.time.ZonedDateTime;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
public abstract class AbstractTriggerRepositoryTest { public abstract class AbstractTriggerRepositoryTest {
@@ -36,21 +35,21 @@ public abstract class AbstractTriggerRepositoryTest {
Trigger.TriggerBuilder<?, ?> builder = trigger(); Trigger.TriggerBuilder<?, ?> builder = trigger();
Optional<Trigger> findLast = triggerRepository.findLast(builder.build()); Optional<Trigger> findLast = triggerRepository.findLast(builder.build());
assertThat(findLast.isPresent(), is(false)); assertThat(findLast.isPresent()).isEqualTo(false);
Trigger save = triggerRepository.save(builder.build()); Trigger save = triggerRepository.save(builder.build());
findLast = triggerRepository.findLast(save); findLast = triggerRepository.findLast(save);
assertThat(findLast.isPresent(), is(true)); assertThat(findLast.isPresent()).isEqualTo(true);
assertThat(findLast.get().getExecutionId(), is(save.getExecutionId())); assertThat(findLast.get().getExecutionId()).isEqualTo(save.getExecutionId());
save = triggerRepository.save(builder.executionId(IdUtils.create()).build()); save = triggerRepository.save(builder.executionId(IdUtils.create()).build());
findLast = triggerRepository.findLast(save); findLast = triggerRepository.findLast(save);
assertThat(findLast.isPresent(), is(true)); assertThat(findLast.isPresent()).isEqualTo(true);
assertThat(findLast.get().getExecutionId(), is(save.getExecutionId())); assertThat(findLast.get().getExecutionId()).isEqualTo(save.getExecutionId());
triggerRepository.save(trigger().build()); triggerRepository.save(trigger().build());
@@ -60,11 +59,11 @@ public abstract class AbstractTriggerRepositoryTest {
List<Trigger> all = triggerRepository.findAllForAllTenants(); List<Trigger> all = triggerRepository.findAllForAllTenants();
assertThat(all.size(), is(4)); assertThat(all.size()).isEqualTo(4);
all = triggerRepository.findAll(null); all = triggerRepository.findAll(null);
assertThat(all.size(), is(4)); assertThat(all.size()).isEqualTo(4);
String namespacePrefix = "io.kestra.another"; String namespacePrefix = "io.kestra.another";
String namespace = namespacePrefix + ".ns"; String namespace = namespacePrefix + ".ns";
@@ -72,30 +71,30 @@ public abstract class AbstractTriggerRepositoryTest {
triggerRepository.save(trigger); triggerRepository.save(trigger);
List<Trigger> find = triggerRepository.find(Pageable.from(1, 4, Sort.of(Sort.Order.asc("namespace"))), null, null, null, null, null); List<Trigger> find = triggerRepository.find(Pageable.from(1, 4, Sort.of(Sort.Order.asc("namespace"))), null, null, null, null, null);
assertThat(find.size(), is(4)); assertThat(find.size()).isEqualTo(4);
assertThat(find.getFirst().getNamespace(), is(namespace)); assertThat(find.getFirst().getNamespace()).isEqualTo(namespace);
find = triggerRepository.find(Pageable.from(1, 4, Sort.of(Sort.Order.asc("namespace"))), null, null, null, searchedTrigger.getFlowId(), null); find = triggerRepository.find(Pageable.from(1, 4, Sort.of(Sort.Order.asc("namespace"))), null, null, null, searchedTrigger.getFlowId(), null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getFlowId(), is(searchedTrigger.getFlowId())); assertThat(find.getFirst().getFlowId()).isEqualTo(searchedTrigger.getFlowId());
find = triggerRepository.find(Pageable.from(1, 100, Sort.of(Sort.Order.asc(triggerRepository.sortMapping().apply("triggerId")))), null, null, namespacePrefix, null, null); find = triggerRepository.find(Pageable.from(1, 100, Sort.of(Sort.Order.asc(triggerRepository.sortMapping().apply("triggerId")))), null, null, namespacePrefix, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getTriggerId(), is(trigger.getTriggerId())); assertThat(find.getFirst().getTriggerId()).isEqualTo(trigger.getTriggerId());
// Full text search is on namespace, flowId, triggerId, executionId // Full text search is on namespace, flowId, triggerId, executionId
find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), trigger.getNamespace(), null, null, null, null); find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), trigger.getNamespace(), null, null, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getTriggerId(), is(trigger.getTriggerId())); assertThat(find.getFirst().getTriggerId()).isEqualTo(trigger.getTriggerId());
find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getFlowId(), null, null, null, null); find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getFlowId(), null, null, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getTriggerId(), is(searchedTrigger.getTriggerId())); assertThat(find.getFirst().getTriggerId()).isEqualTo(searchedTrigger.getTriggerId());
find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getTriggerId(), null, null, null, null); find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getTriggerId(), null, null, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getTriggerId(), is(searchedTrigger.getTriggerId())); assertThat(find.getFirst().getTriggerId()).isEqualTo(searchedTrigger.getTriggerId());
find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getExecutionId(), null, null, null, null); find = triggerRepository.find(Pageable.from(1, 100, Sort.UNSORTED), searchedTrigger.getExecutionId(), null, null, null, null);
assertThat(find.size(), is(1)); assertThat(find.size()).isEqualTo(1);
assertThat(find.getFirst().getTriggerId(), is(searchedTrigger.getTriggerId())); assertThat(find.getFirst().getTriggerId()).isEqualTo(searchedTrigger.getTriggerId());
} }
@Test @Test
@@ -111,7 +110,7 @@ public abstract class AbstractTriggerRepositoryTest {
// When // When
int count = triggerRepository.count(null); int count = triggerRepository.count(null);
// Then // Then
assertThat(count, is(1)); assertThat(count).isEqualTo(1);
} }
@Test @Test
@@ -143,9 +142,9 @@ public abstract class AbstractTriggerRepositoryTest {
// When // When
int count = triggerRepository.countForNamespace(null, "io.kestra.unittest.shouldcountbynamespacefornulltenant"); int count = triggerRepository.countForNamespace(null, "io.kestra.unittest.shouldcountbynamespacefornulltenant");
assertThat(count, is(1)); assertThat(count).isEqualTo(1);
count = triggerRepository.countForNamespace(null, "io.kestra.unittest"); count = triggerRepository.countForNamespace(null, "io.kestra.unittest");
assertThat(count, is(2)); assertThat(count).isEqualTo(2);
} }
} }

View File

@@ -1,7 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import io.kestra.core.junit.annotations.ExecuteFlow; import io.kestra.core.junit.annotations.ExecuteFlow;
import io.kestra.core.junit.annotations.KestraTest; import io.kestra.core.junit.annotations.KestraTest;
@@ -90,66 +89,63 @@ public abstract class AbstractRunnerTest {
@Test @Test
@ExecuteFlow("flows/valids/full.yaml") @ExecuteFlow("flows/valids/full.yaml")
void full(Execution execution) { void full(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(13)); assertThat(execution.getTaskRunList()).hasSize(13);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat( assertThat((String) execution.findTaskRunsByTaskId("t2").getFirst().getOutputs().get("value")).contains("value1");
(String) execution.findTaskRunsByTaskId("t2").getFirst().getOutputs().get("value"),
containsString("value1"));
} }
@Test @Test
@ExecuteFlow("flows/valids/logs.yaml") @ExecuteFlow("flows/valids/logs.yaml")
void logs(Execution execution) { void logs(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(5)); assertThat(execution.getTaskRunList()).hasSize(5);
} }
@Test @Test
@ExecuteFlow("flows/valids/sequential.yaml") @ExecuteFlow("flows/valids/sequential.yaml")
void sequential(Execution execution) { void sequential(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
} }
@Test @Test
@ExecuteFlow("flows/valids/parallel.yaml") @ExecuteFlow("flows/valids/parallel.yaml")
void parallel(Execution execution) { void parallel(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(8)); assertThat(execution.getTaskRunList()).hasSize(8);
} }
@RetryingTest(5) @RetryingTest(5)
@ExecuteFlow("flows/valids/parallel-nested.yaml") @ExecuteFlow("flows/valids/parallel-nested.yaml")
void parallelNested(Execution execution) { void parallelNested(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
} }
@Test @Test
@ExecuteFlow("flows/valids/each-parallel-subflow-notfound.yml") @ExecuteFlow("flows/valids/each-parallel-subflow-notfound.yml")
void eachParallelWithSubflowMissing(Execution execution) { void eachParallelWithSubflowMissing(Execution execution) {
assertThat(execution, notNullValue()); assertThat(execution).isNotNull();
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
// on JDBC, when using an each parallel, the flow is failed even if not all subtasks of the each parallel are ended as soon as // on JDBC, when using an each parallel, the flow is failed even if not all subtasks of the each parallel are ended as soon as
// there is one failed task FIXME https://github.com/kestra-io/kestra/issues/2179 // there is one failed task FIXME https://github.com/kestra-io/kestra/issues/2179
// so instead of asserting that all tasks FAILED we assert that at least two failed (the each parallel and one of its subtasks) // so instead of asserting that all tasks FAILED we assert that at least two failed (the each parallel and one of its subtasks)
assertThat( assertThat(execution.getTaskRunList().stream().filter(taskRun -> taskRun.getState().isFailed())
execution.getTaskRunList().stream().filter(taskRun -> taskRun.getState().isFailed()) .count()).isGreaterThanOrEqualTo(2L); // Should be 3
.count(), greaterThanOrEqualTo(2L)); // Should be 3
} }
@Test @Test
@ExecuteFlow("flows/valids/each-sequential-nested.yaml") @ExecuteFlow("flows/valids/each-sequential-nested.yaml")
void eachSequentialNested(Execution execution) { void eachSequentialNested(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(23)); assertThat(execution.getTaskRunList()).hasSize(23);
} }
@Test @Test
@ExecuteFlow("flows/valids/each-parallel.yaml") @ExecuteFlow("flows/valids/each-parallel.yaml")
void eachParallel(Execution execution) { void eachParallel(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(8)); assertThat(execution.getTaskRunList()).hasSize(8);
} }
@Test @Test
@ExecuteFlow("flows/valids/each-parallel-nested.yaml") @ExecuteFlow("flows/valids/each-parallel-nested.yaml")
void eachParallelNested(Execution execution) { void eachParallelNested(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
} }
@Test @Test
@@ -405,16 +401,16 @@ public abstract class AbstractRunnerTest {
@Test @Test
@ExecuteFlow("flows/valids/executable-fail.yml") @ExecuteFlow("flows/valids/executable-fail.yml")
void badExecutable(Execution execution) { void badExecutable(Execution execution) {
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
@Test @Test
@ExecuteFlow("flows/valids/dynamic-task.yaml") @ExecuteFlow("flows/valids/dynamic-task.yaml")
void dynamicTask(Execution execution) { void dynamicTask(Execution execution) {
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
@Test @Test
@@ -495,8 +491,8 @@ public abstract class AbstractRunnerTest {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "if", null, Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "if", null,
(f, e) -> Map.of("if1", true, "if2", false, "if3", true)); (f, e) -> Map.of("if1", true, "if2", false, "if3", true));
assertThat(execution.getTaskRunList(), hasSize(12)); assertThat(execution.getTaskRunList()).hasSize(12);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
@Test @Test

View File

@@ -8,89 +8,86 @@ import java.util.Map;
import static io.kestra.core.models.flows.State.Type.FAILED; import static io.kestra.core.models.flows.State.Type.FAILED;
import static io.kestra.core.models.flows.State.Type.SUCCESS; import static io.kestra.core.models.flows.State.Type.SUCCESS;
import static org.exparity.hamcrest.date.InstantMatchers.sameOrAfter; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@Singleton @Singleton
public class AfterExecutionTestCase { public class AfterExecutionTestCase {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void shouldCallTasksAfterExecution(Execution execution) { public void shouldCallTasksAfterExecution(Execution execution) {
assertThat(execution.getState().getCurrent(), is(SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
TaskRun taskRun = execution.getTaskRunList().getFirst(); TaskRun taskRun = execution.getTaskRunList().getFirst();
assertThat(taskRun.getTaskId(), is("hello")); assertThat(taskRun.getTaskId()).isEqualTo("hello");
assertThat(taskRun.getState().getCurrent(), is(SUCCESS)); assertThat(taskRun.getState().getCurrent()).isEqualTo(SUCCESS);
TaskRun afterExecution = execution.getTaskRunList().getLast(); TaskRun afterExecution = execution.getTaskRunList().getLast();
assertThat(afterExecution.getTaskId(), is("end")); assertThat(afterExecution.getTaskId()).isEqualTo("end");
assertThat(afterExecution.getState().getCurrent(), is(SUCCESS)); assertThat(afterExecution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(taskRun.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(taskRun.getState().getEndDate().orElseThrow());
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(execution.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(execution.getState().getEndDate().orElseThrow());
Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values"); Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values");
assertThat(outputs.get("state"), is("SUCCESS")); assertThat(outputs.get("state")).isEqualTo("SUCCESS");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void shouldCallTasksAfterFinally(Execution execution) { public void shouldCallTasksAfterFinally(Execution execution) {
assertThat(execution.getState().getCurrent(), is(SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
TaskRun taskRun = execution.getTaskRunList().getFirst(); TaskRun taskRun = execution.getTaskRunList().getFirst();
assertThat(taskRun.getState().getCurrent(), is(SUCCESS)); assertThat(taskRun.getState().getCurrent()).isEqualTo(SUCCESS);
TaskRun finallyTaskRun = execution.getTaskRunList().get(1); TaskRun finallyTaskRun = execution.getTaskRunList().get(1);
assertThat(finallyTaskRun.getState().getCurrent(), is(SUCCESS)); assertThat(finallyTaskRun.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(finallyTaskRun.getState().getStartDate(), sameOrAfter(taskRun.getState().getEndDate().orElseThrow())); assertThat(finallyTaskRun.getState().getStartDate()).isAfterOrEqualTo(taskRun.getState().getEndDate().orElseThrow());
TaskRun afterExecution = execution.getTaskRunList().getLast(); TaskRun afterExecution = execution.getTaskRunList().getLast();
assertThat(afterExecution.getState().getCurrent(), is(SUCCESS)); assertThat(afterExecution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(finallyTaskRun.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(finallyTaskRun.getState().getEndDate().orElseThrow());
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(execution.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(execution.getState().getEndDate().orElseThrow());
Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values"); Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values");
assertThat(outputs.get("state"), is("SUCCESS")); assertThat(outputs.get("state")).isEqualTo("SUCCESS");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void shouldCallTasksAfterError(Execution execution) { public void shouldCallTasksAfterError(Execution execution) {
assertThat(execution.getState().getCurrent(), is(FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(FAILED);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
TaskRun taskRun = execution.getTaskRunList().getFirst(); TaskRun taskRun = execution.getTaskRunList().getFirst();
assertThat(taskRun.getState().getCurrent(), is(FAILED)); assertThat(taskRun.getState().getCurrent()).isEqualTo(FAILED);
TaskRun errorTaskRun = execution.getTaskRunList().get(1); TaskRun errorTaskRun = execution.getTaskRunList().get(1);
assertThat(errorTaskRun.getState().getCurrent(), is(SUCCESS)); assertThat(errorTaskRun.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(errorTaskRun.getState().getStartDate(), sameOrAfter(taskRun.getState().getEndDate().orElseThrow())); assertThat(errorTaskRun.getState().getStartDate()).isAfterOrEqualTo(taskRun.getState().getEndDate().orElseThrow());
TaskRun afterExecution = execution.getTaskRunList().getLast(); TaskRun afterExecution = execution.getTaskRunList().getLast();
assertThat(afterExecution.getState().getCurrent(), is(SUCCESS)); assertThat(afterExecution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(taskRun.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(taskRun.getState().getEndDate().orElseThrow());
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(execution.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(execution.getState().getEndDate().orElseThrow());
Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values"); Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values");
assertThat(outputs.get("state"), is("FAILED")); assertThat(outputs.get("state")).isEqualTo("FAILED");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void shouldCallTasksAfterListener(Execution execution) { public void shouldCallTasksAfterListener(Execution execution) {
assertThat(execution.getState().getCurrent(), is(SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
TaskRun taskRun = execution.getTaskRunList().getFirst(); TaskRun taskRun = execution.getTaskRunList().getFirst();
assertThat(taskRun.getState().getCurrent(), is(SUCCESS)); assertThat(taskRun.getState().getCurrent()).isEqualTo(SUCCESS);
TaskRun listenerTaskRun = execution.getTaskRunList().get(1); TaskRun listenerTaskRun = execution.getTaskRunList().get(1);
assertThat(taskRun.getState().getCurrent(), is(SUCCESS)); assertThat(taskRun.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(listenerTaskRun.getState().getStartDate(), sameOrAfter(taskRun.getState().getEndDate().orElseThrow())); assertThat(listenerTaskRun.getState().getStartDate()).isAfterOrEqualTo(taskRun.getState().getEndDate().orElseThrow());
TaskRun afterExecution = execution.getTaskRunList().getLast(); TaskRun afterExecution = execution.getTaskRunList().getLast();
assertThat(afterExecution.getState().getCurrent(), is(SUCCESS)); assertThat(afterExecution.getState().getCurrent()).isEqualTo(SUCCESS);
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(listenerTaskRun.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(listenerTaskRun.getState().getEndDate().orElseThrow());
assertThat(afterExecution.getState().getStartDate(), sameOrAfter(execution.getState().getEndDate().orElseThrow())); assertThat(afterExecution.getState().getStartDate()).isAfterOrEqualTo(execution.getState().getEndDate().orElseThrow());
Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values"); Map<String, Object> outputs = (Map<String, Object> ) afterExecution.getOutputs().get("values");
assertThat(outputs.get("state"), is("SUCCESS")); assertThat(outputs.get("state")).isEqualTo("SUCCESS");
} }
} }

View File

@@ -1,7 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import io.kestra.core.junit.annotations.ExecuteFlow; import io.kestra.core.junit.annotations.ExecuteFlow;
import io.kestra.core.junit.annotations.KestraTest; import io.kestra.core.junit.annotations.KestraTest;
@@ -15,14 +14,14 @@ public class AliasTest {
@Test @Test
@ExecuteFlow("flows/valids/alias-task.yaml") @ExecuteFlow("flows/valids/alias-task.yaml")
void taskAlias(Execution execution) { void taskAlias(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList().size(), is(2)); assertThat(execution.getTaskRunList().size()).isEqualTo(2);
} }
@Test @Test
@ExecuteFlow("flows/valids/alias-trigger.yaml") @ExecuteFlow("flows/valids/alias-trigger.yaml")
void triggerAlias(Execution execution) { void triggerAlias(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
} }
} }

View File

@@ -17,8 +17,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@Singleton @Singleton
public class ChangeStateTestCase { public class ChangeStateTestCase {
@@ -36,9 +35,9 @@ public class ChangeStateTestCase {
private RunnerUtils runnerUtils; private RunnerUtils runnerUtils;
public void changeStateShouldEndsInSuccess(Execution execution) throws Exception { public void changeStateShouldEndsInSuccess(Execution execution) throws Exception {
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
// await for the last execution // await for the last execution
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
@@ -55,11 +54,11 @@ public class ChangeStateTestCase {
Execution markedAs = executionService.markAs(execution, flow, execution.getTaskRunList().getFirst().getId(), State.Type.SUCCESS); Execution markedAs = executionService.markAs(execution, flow, execution.getTaskRunList().getFirst().getId(), State.Type.SUCCESS);
executionQueue.emit(markedAs); executionQueue.emit(markedAs);
assertThat(latch.await(10, TimeUnit.SECONDS), is(true)); assertThat(latch.await(10, TimeUnit.SECONDS)).isEqualTo(true);
receivedExecutions.blockLast(); receivedExecutions.blockLast();
assertThat(lastExecution.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(lastExecution.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(lastExecution.get().getTaskRunList(), hasSize(2)); assertThat(lastExecution.get().getTaskRunList()).hasSize(2);
assertThat(lastExecution.get().getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(lastExecution.get().getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
public void changeStateInSubflowShouldEndsParentFlowInSuccess() throws Exception { public void changeStateInSubflowShouldEndsParentFlowInSuccess() throws Exception {
@@ -76,16 +75,16 @@ public class ChangeStateTestCase {
// run the parent flow // run the parent flow
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "subflow-parent-of-failed"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "subflow-parent-of-failed");
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
// assert on the subflow // assert on the subflow
assertThat(latch.await(10, TimeUnit.SECONDS), is(true)); assertThat(latch.await(10, TimeUnit.SECONDS)).isEqualTo(true);
receivedExecutions.blockLast(); receivedExecutions.blockLast();
assertThat(lastExecution.get().getState().getCurrent(), is(State.Type.FAILED)); assertThat(lastExecution.get().getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(lastExecution.get().getTaskRunList(), hasSize(1)); assertThat(lastExecution.get().getTaskRunList()).hasSize(1);
assertThat(lastExecution.get().getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(lastExecution.get().getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
// await for the parent execution // await for the parent execution
CountDownLatch parentLatch = new CountDownLatch(1); CountDownLatch parentLatch = new CountDownLatch(1);
@@ -104,10 +103,10 @@ public class ChangeStateTestCase {
executionQueue.emit(markedAs); executionQueue.emit(markedAs);
// assert for the parent flow // assert for the parent flow
assertThat(parentLatch.await(10, TimeUnit.SECONDS), is(true)); assertThat(parentLatch.await(10, TimeUnit.SECONDS)).isEqualTo(true);
receivedExecutions.blockLast(); receivedExecutions.blockLast();
assertThat(lastParentExecution.get().getState().getCurrent(), is(State.Type.FAILED)); // FIXME should be success but it's FAILED on unit tests assertThat(lastParentExecution.get().getState().getCurrent()).isEqualTo(State.Type.FAILED); // FIXME should be success but it's FAILED on unit tests
assertThat(lastParentExecution.get().getTaskRunList(), hasSize(1)); assertThat(lastParentExecution.get().getTaskRunList()).hasSize(1);
assertThat(lastParentExecution.get().getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(lastParentExecution.get().getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
} }

View File

@@ -13,8 +13,7 @@ import org.junit.jupiter.api.Test;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@MicronautTest @MicronautTest
class DefaultRunContextTest { class DefaultRunContextTest {
@@ -44,6 +43,6 @@ class DefaultRunContextTest {
"secret", Map.of("type", EncryptedString.TYPE, "value", encryptedSecret)); "secret", Map.of("type", EncryptedString.TYPE, "value", encryptedSecret));
String render = runContext.render("What ? {{secret}}", variables); String render = runContext.render("What ? {{secret}}", variables);
assertThat(render, is(("What ? It's a secret"))); assertThat(render).isEqualTo(("What ? It's a secret"));
} }
} }

View File

@@ -22,8 +22,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@Singleton @Singleton
public class DeserializationIssuesCaseTest { public class DeserializationIssuesCaseTest {
@@ -245,9 +244,9 @@ public class DeserializationIssuesCaseTest {
Duration.ofMinutes(1) Duration.ofMinutes(1)
); );
receive.blockLast(); receive.blockLast();
assertThat(workerTaskResult.get().getTaskRun().getState().getHistories().size(), is(2)); assertThat(workerTaskResult.get().getTaskRun().getState().getHistories().size()).isEqualTo(2);
assertThat(workerTaskResult.get().getTaskRun().getState().getHistories().getFirst().getState(), is(State.Type.CREATED)); assertThat(workerTaskResult.get().getTaskRun().getState().getHistories().getFirst().getState()).isEqualTo(State.Type.CREATED);
assertThat(workerTaskResult.get().getTaskRun().getState().getCurrent(), is(State.Type.FAILED)); assertThat(workerTaskResult.get().getTaskRun().getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
public void workerTriggerDeserializationIssue(Consumer<QueueMessage> sendToQueue) throws TimeoutException, QueueException{ public void workerTriggerDeserializationIssue(Consumer<QueueMessage> sendToQueue) throws TimeoutException, QueueException{
@@ -266,7 +265,7 @@ public class DeserializationIssuesCaseTest {
Duration.ofMinutes(1) Duration.ofMinutes(1)
); );
receive.blockLast(); receive.blockLast();
assertThat(workerTriggerResult.get().getSuccess(), is(Boolean.FALSE)); assertThat(workerTriggerResult.get().getSuccess()).isEqualTo(Boolean.FALSE);
} }
public void flowDeserializationIssue(Consumer<QueueMessage> sendToQueue) throws Exception { public void flowDeserializationIssue(Consumer<QueueMessage> sendToQueue) throws Exception {

View File

@@ -1,7 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import io.kestra.core.junit.annotations.ExecuteFlow; import io.kestra.core.junit.annotations.ExecuteFlow;
import io.kestra.core.junit.annotations.KestraTest; import io.kestra.core.junit.annotations.KestraTest;
@@ -13,18 +12,18 @@ public class DisabledTest {
@Test @Test
@ExecuteFlow("flows/valids/disable-simple.yaml") @ExecuteFlow("flows/valids/disable-simple.yaml")
void simple(Execution execution) { void simple(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
} }
@Test @Test
@ExecuteFlow("flows/valids/disable-error.yaml") @ExecuteFlow("flows/valids/disable-error.yaml")
void error(Execution execution) { void error(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
} }
@Test @Test
@ExecuteFlow("flows/valids/disable-flowable.yaml") @ExecuteFlow("flows/valids/disable-flowable.yaml")
void flowable(Execution execution) { void flowable(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(10)); assertThat(execution.getTaskRunList()).hasSize(10);
} }
} }

View File

@@ -11,8 +11,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
public class EmptyVariablesTest { public class EmptyVariablesTest {
@@ -33,8 +32,8 @@ public class EmptyVariablesTest {
(flow, exec) -> flowIO.readExecutionInputs(flow, exec, Map.of("emptyKey", "{ \"foo\": \"\" }", "emptySubObject", "{\"json\":{\"someEmptyObject\":{}}}")) (flow, exec) -> flowIO.readExecutionInputs(flow, exec, Map.of("emptyKey", "{ \"foo\": \"\" }", "emptySubObject", "{\"json\":{\"someEmptyObject\":{}}}"))
); );
assertThat(execution, notNullValue()); assertThat(execution).isNotNull();
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
} }
} }

View File

@@ -29,8 +29,10 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@Slf4j @Slf4j
@@ -55,27 +57,27 @@ class ExecutionServiceTest {
@LoadFlows({"flows/valids/restart_last_failed.yaml"}) @LoadFlows({"flows/valids/restart_last_failed.yaml"})
void restartSimple() throws Exception { void restartSimple() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart_last_failed"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart_last_failed");
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution restart = executionService.restart(execution, null); Execution restart = executionService.restart(execution, null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(3)); assertThat(restart.getTaskRunList()).hasSize(3);
assertThat(restart.getTaskRunList().get(2).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().get(2).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getTaskRunList().get(2).getState().getHistories(), hasSize(4)); assertThat(restart.getTaskRunList().get(2).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), is(execution.getId())); assertThat(restart.getId()).isEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(2).getId(), is(execution.getTaskRunList().get(2).getId())); assertThat(restart.getTaskRunList().get(2).getId()).isEqualTo(execution.getTaskRunList().get(2).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.RESTARTED, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.RESTARTED, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/restart_last_failed.yaml"}) @LoadFlows({"flows/valids/restart_last_failed.yaml"})
void restartSimpleRevision() throws Exception { void restartSimpleRevision() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart_last_failed"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart_last_failed");
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
FlowWithSource flow = flowRepository.findByIdWithSource(null, "io.kestra.tests", "restart_last_failed").orElseThrow(); FlowWithSource flow = flowRepository.findByIdWithSource(null, "io.kestra.tests", "restart_last_failed").orElseThrow();
flowRepository.update( flowRepository.update(
@@ -93,220 +95,220 @@ class ExecutionServiceTest {
Execution restart = executionService.restart(execution, 2); Execution restart = executionService.restart(execution, 2);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(3)); assertThat(restart.getTaskRunList()).hasSize(3);
assertThat(restart.getTaskRunList().get(2).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().get(2).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getTaskRunList().get(2).getState().getHistories(), hasSize(4)); assertThat(restart.getTaskRunList().get(2).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(2).getId(), not(execution.getTaskRunList().get(2).getId())); assertThat(restart.getTaskRunList().get(2).getId()).isNotEqualTo(execution.getTaskRunList().get(2).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.RESTARTED, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.RESTARTED, "true"));
} }
@RetryingTest(5) @RetryingTest(5)
@LoadFlows({"flows/valids/restart-each.yaml"}) @LoadFlows({"flows/valids/restart-each.yaml"})
void restartFlowable() throws Exception { void restartFlowable() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "FIRST")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "FIRST"));
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution restart = executionService.restart(execution, null); Execution restart = executionService.restart(execution, null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RESTARTED).count(), greaterThan(1L)); assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RESTARTED).count()).isGreaterThan(1L);
assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RUNNING).count(), greaterThan(1L)); assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RUNNING).count()).isGreaterThan(1L);
assertThat(restart.getTaskRunList().getFirst().getId(), is(restart.getTaskRunList().getFirst().getId())); assertThat(restart.getTaskRunList().getFirst().getId()).isEqualTo(restart.getTaskRunList().getFirst().getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.RESTARTED, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.RESTARTED, "true"));
} }
@RetryingTest(5) @RetryingTest(5)
@LoadFlows({"flows/valids/restart-each.yaml"}) @LoadFlows({"flows/valids/restart-each.yaml"})
void restartFlowable2() throws Exception { void restartFlowable2() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "SECOND")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "SECOND"));
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution restart = executionService.restart(execution, null); Execution restart = executionService.restart(execution, null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RESTARTED).count(), greaterThan(1L)); assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RESTARTED).count()).isGreaterThan(1L);
assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RUNNING).count(), greaterThan(1L)); assertThat(restart.getTaskRunList().stream().filter(taskRun -> taskRun.getState().getCurrent() == State.Type.RUNNING).count()).isGreaterThan(1L);
assertThat(restart.getTaskRunList().getFirst().getId(), is(restart.getTaskRunList().getFirst().getId())); assertThat(restart.getTaskRunList().getFirst().getId()).isEqualTo(restart.getTaskRunList().getFirst().getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.RESTARTED, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.RESTARTED, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/working-directory.yaml"}) @LoadFlows({"flows/valids/working-directory.yaml"})
void restartDynamic() throws Exception { void restartDynamic() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "working-directory", null, (f, e) -> ImmutableMap.of("failed", "true")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "working-directory", null, (f, e) -> ImmutableMap.of("failed", "true"));
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution restart = executionService.restart(execution, null); Execution restart = executionService.restart(execution, null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getTaskRunList().getFirst().getState().getHistories(), hasSize(4)); assertThat(restart.getTaskRunList().getFirst().getState().getHistories()).hasSize(4);
assertThat(restart.getLabels(), hasItem(new Label(Label.RESTARTED, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.RESTARTED, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/logs.yaml"}) @LoadFlows({"flows/valids/logs.yaml"})
void replayFromBeginning() throws Exception { void replayFromBeginning() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs");
assertThat(execution.getTaskRunList(), hasSize(5)); assertThat(execution.getTaskRunList()).hasSize(5);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, null, null); Execution restart = executionService.replay(execution, null, null);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getNamespace(), is("io.kestra.tests")); assertThat(restart.getNamespace()).isEqualTo("io.kestra.tests");
assertThat(restart.getFlowId(), is("logs")); assertThat(restart.getFlowId()).isEqualTo("logs");
assertThat(restart.getState().getCurrent(), is(State.Type.CREATED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.CREATED);
assertThat(restart.getState().getHistories(), hasSize(1)); assertThat(restart.getState().getHistories()).hasSize(1);
assertThat(restart.getState().getHistories().getFirst().getDate(), not(is(execution.getState().getStartDate()))); assertThat(restart.getState().getHistories().getFirst().getDate(), not(is(execution.getState().getStartDate())));
assertThat(restart.getTaskRunList(), hasSize(0)); assertThat(restart.getTaskRunList()).hasSize(0);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/logs.yaml"}) @LoadFlows({"flows/valids/logs.yaml"})
void replaySimple() throws Exception { void replaySimple() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs");
assertThat(execution.getTaskRunList(), hasSize(5)); assertThat(execution.getTaskRunList()).hasSize(5);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.getTaskRunList().get(1).getId(), null); Execution restart = executionService.replay(execution, execution.getTaskRunList().get(1).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(2)); assertThat(restart.getTaskRunList()).hasSize(2);
assertThat(restart.getTaskRunList().get(1).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().get(1).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getTaskRunList().get(1).getState().getHistories(), hasSize(4)); assertThat(restart.getTaskRunList().get(1).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/restart-each.yaml"}) @LoadFlows({"flows/valids/restart-each.yaml"})
void replayFlowable() throws Exception { void replayFlowable() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "NO")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-each", null, (f, e) -> ImmutableMap.of("failed", "NO"));
assertThat(execution.getTaskRunList(), hasSize(20)); assertThat(execution.getTaskRunList()).hasSize(20);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("2_end", List.of()).getId(), null); Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("2_end", List.of()).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(20)); assertThat(restart.getTaskRunList()).hasSize(20);
assertThat(restart.getTaskRunList().get(19).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().get(19).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/parallel-nested.yaml"}) @LoadFlows({"flows/valids/parallel-nested.yaml"})
void replayParallel() throws Exception { void replayParallel() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "parallel-nested"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "parallel-nested");
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getId(), null); Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(8)); assertThat(restart.getTaskRunList()).hasSize(8);
assertThat(restart.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("1-3-2_par", List.of()).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/each-sequential-nested.yaml"}) @LoadFlows({"flows/valids/each-sequential-nested.yaml"})
void replayEachSeq() throws Exception { void replayEachSeq() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested");
assertThat(execution.getTaskRunList(), hasSize(23)); assertThat(execution.getTaskRunList()).hasSize(23);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getId(), null); Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(5)); assertThat(restart.getTaskRunList()).hasSize(5);
assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/each-sequential-nested.yaml"}) @LoadFlows({"flows/valids/each-sequential-nested.yaml"})
void replayEachSeq2() throws Exception { void replayEachSeq2() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested");
assertThat(execution.getTaskRunList(), hasSize(23)); assertThat(execution.getTaskRunList()).hasSize(23);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-2-1_return", List.of("s1", "a a")).getId(), null); Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("1-2-1_return", List.of("s1", "a a")).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(6)); assertThat(restart.getTaskRunList()).hasSize(6);
assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("1-2_each", List.of("s1")).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/dynamic-task.yaml"}) @LoadFlows({"flows/valids/dynamic-task.yaml"})
void replayWithADynamicTask() throws Exception { void replayWithADynamicTask() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "dynamic-task"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "dynamic-task");
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.getTaskRunList().get(2).getId(), null); Execution restart = executionService.replay(execution, execution.getTaskRunList().get(2).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(3)); assertThat(restart.getTaskRunList()).hasSize(3);
assertThat(restart.getTaskRunList().get(2).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getTaskRunList().get(2).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getTaskRunList().get(2).getState().getHistories(), hasSize(4)); assertThat(restart.getTaskRunList().get(2).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@LoadFlows({"flows/valids/each-parallel-nested.yaml"}) @LoadFlows({"flows/valids/each-parallel-nested.yaml"})
void replayEachPara() throws Exception { void replayEachPara() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-parallel-nested"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-parallel-nested");
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getId(), null); Execution restart = executionService.replay(execution, execution.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getId(), null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(8)); assertThat(restart.getTaskRunList()).hasSize(8);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getHistories()).hasSize(4);
assertThat(restart.getId(), not(execution.getId())); assertThat(restart.getId()).isNotEqualTo(execution.getId());
assertThat(restart.getTaskRunList().get(1).getId(), not(execution.getTaskRunList().get(1).getId())); assertThat(restart.getTaskRunList().get(1).getId()).isNotEqualTo(execution.getTaskRunList().get(1).getId());
assertThat(restart.getLabels(), hasItem(new Label(Label.REPLAY, "true"))); assertThat(restart.getLabels()).contains(new Label(Label.REPLAY, "true"));
} }
@Test @Test
@@ -315,30 +317,30 @@ class ExecutionServiceTest {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-parallel-nested"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-parallel-nested");
Flow flow = flowRepository.findByExecution(execution); Flow flow = flowRepository.findByExecution(execution);
assertThat(execution.getTaskRunList(), hasSize(11)); assertThat(execution.getTaskRunList()).hasSize(11);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Execution restart = executionService.markAs(execution, flow, execution.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getId(), State.Type.FAILED); Execution restart = executionService.markAs(execution, flow, execution.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getId(), State.Type.FAILED);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getMetadata().getAttemptNumber(), is(2)); assertThat(restart.getMetadata().getAttemptNumber()).isEqualTo(2);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(11)); assertThat(restart.getTaskRunList()).hasSize(11);
assertThat(restart.findTaskRunByTaskIdAndValue("1_each", List.of()).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("1_each", List.of()).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent(), is(State.Type.FAILED)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getHistories()).hasSize(4);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getAttempts(), nullValue()); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getAttempts()).isNull();
restart = executionService.markAs(execution, flow, execution.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getId(), State.Type.FAILED); restart = executionService.markAs(execution, flow, execution.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getId(), State.Type.FAILED);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restart.getState().getHistories(), hasSize(4)); assertThat(restart.getState().getHistories()).hasSize(4);
assertThat(restart.getTaskRunList(), hasSize(11)); assertThat(restart.getTaskRunList()).hasSize(11);
assertThat(restart.findTaskRunByTaskIdAndValue("1_each", List.of()).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("1_each", List.of()).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent(), is(State.Type.RUNNING)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1_seq", List.of("value 1")).getState().getCurrent()).isEqualTo(State.Type.RUNNING);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getState().getCurrent(), is(State.Type.FAILED)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getState().getHistories(), hasSize(4)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getState().getHistories()).hasSize(4);
assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getAttempts().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(restart.findTaskRunByTaskIdAndValue("2-1-2_t2", List.of("value 1")).getAttempts().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
@Test @Test
@@ -347,13 +349,13 @@ class ExecutionServiceTest {
Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause"); Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause");
Flow flow = flowRepository.findByExecution(execution); Flow flow = flowRepository.findByExecution(execution);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.PAUSED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.PAUSED);
Execution resume = executionService.resume(execution, flow, State.Type.RUNNING); Execution resume = executionService.resume(execution, flow, State.Type.RUNNING);
assertThat(resume.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(resume.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(resume.getState().getHistories(), hasSize(4)); assertThat(resume.getState().getHistories()).hasSize(4);
assertThrows( assertThrows(
IllegalArgumentException.class, IllegalArgumentException.class,
@@ -367,36 +369,36 @@ class ExecutionServiceTest {
Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause"); Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause");
Flow flow = flowRepository.findByExecution(execution); Flow flow = flowRepository.findByExecution(execution);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.PAUSED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.PAUSED);
Execution resume = executionService.resume(execution, flow, State.Type.KILLING); Execution resume = executionService.resume(execution, flow, State.Type.KILLING);
assertThat(resume.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(resume.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(resume.getState().getHistories(), hasSize(4)); assertThat(resume.getState().getHistories()).hasSize(4);
} }
@Test @Test
@ExecuteFlow("flows/valids/logs.yaml") @ExecuteFlow("flows/valids/logs.yaml")
void deleteExecution(Execution execution) throws IOException, TimeoutException { void deleteExecution(Execution execution) throws IOException, TimeoutException {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
Await.until(() -> logRepository.findByExecutionId(execution.getTenantId(), execution.getId(), Level.TRACE).size() == 5, Duration.ofMillis(10), Duration.ofSeconds(5)); Await.until(() -> logRepository.findByExecutionId(execution.getTenantId(), execution.getId(), Level.TRACE).size() == 5, Duration.ofMillis(10), Duration.ofSeconds(5));
executionService.delete(execution, true, true, true); executionService.delete(execution, true, true, true);
assertThat(executionRepository.findById(execution.getTenantId(),execution.getId()), is(Optional.empty())); assertThat(executionRepository.findById(execution.getTenantId(), execution.getId())).isEqualTo(Optional.empty());
assertThat(logRepository.findByExecutionId(execution.getTenantId(), execution.getId(), Level.INFO), empty()); assertThat(logRepository.findByExecutionId(execution.getTenantId(), execution.getId(), Level.INFO)).isEmpty();
} }
@Test @Test
@ExecuteFlow("flows/valids/logs.yaml") @ExecuteFlow("flows/valids/logs.yaml")
void deleteExecutionKeepLogs(Execution execution) throws IOException { void deleteExecutionKeepLogs(Execution execution) throws IOException {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
executionService.delete(execution, false, false, false); executionService.delete(execution, false, false, false);
assertThat(executionRepository.findById(execution.getTenantId(),execution.getId()), is(Optional.empty())); assertThat(executionRepository.findById(execution.getTenantId(), execution.getId())).isEqualTo(Optional.empty());
assertThat(logRepository.findByExecutionId(execution.getTenantId(),execution.getId(), Level.INFO), hasSize(4)); assertThat(logRepository.findByExecutionId(execution.getTenantId(), execution.getId(), Level.INFO)).hasSize(4);
} }
@Test @Test
@@ -405,25 +407,25 @@ class ExecutionServiceTest {
Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause_no_tasks"); Execution execution = runnerUtils.runOneUntilPaused(null, "io.kestra.tests", "pause_no_tasks");
Flow flow = flowRepository.findByExecution(execution); Flow flow = flowRepository.findByExecution(execution);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.PAUSED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.PAUSED);
Execution killed = executionService.kill(execution, flow); Execution killed = executionService.kill(execution, flow);
assertThat(killed.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(killed.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(killed.findTaskRunsByTaskId("pause").getFirst().getState().getCurrent(), is(State.Type.KILLED)); assertThat(killed.findTaskRunsByTaskId("pause").getFirst().getState().getCurrent()).isEqualTo(State.Type.KILLED);
assertThat(killed.getState().getHistories(), hasSize(4)); assertThat(killed.getState().getHistories()).hasSize(4);
} }
@Test @Test
@ExecuteFlow("flows/valids/failed-first.yaml") @ExecuteFlow("flows/valids/failed-first.yaml")
void shouldRestartAfterChangeTaskState(Execution execution) throws Exception { void shouldRestartAfterChangeTaskState(Execution execution) throws Exception {
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
Flow flow = flowRepository.findByExecution(execution); Flow flow = flowRepository.findByExecution(execution);
Execution markedAs = executionService.markAs(execution, flow, execution.getTaskRunList().getFirst().getId(), State.Type.SUCCESS); Execution markedAs = executionService.markAs(execution, flow, execution.getTaskRunList().getFirst().getId(), State.Type.SUCCESS);
assertThat(markedAs.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(markedAs.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
} }
} }

View File

@@ -9,8 +9,7 @@ import java.net.URI;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
class FilesServiceTest { class FilesServiceTest {
@@ -25,21 +24,21 @@ class FilesServiceTest {
FilesService.inputFiles(runContext, Map.of("file.txt", "overriden content")); FilesService.inputFiles(runContext, Map.of("file.txt", "overriden content"));
String fileContent = FileUtils.readFileToString(runContext.workingDir().path().resolve("file.txt").toFile(), "UTF-8"); String fileContent = FileUtils.readFileToString(runContext.workingDir().path().resolve("file.txt").toFile(), "UTF-8");
assertThat(fileContent, is("overriden content")); assertThat(fileContent).isEqualTo("overriden content");
} }
@Test @Test
void renderInputFile() throws Exception { void renderInputFile() throws Exception {
RunContext runContext = runContextFactory.of(Map.of("filename", "file.txt", "content", "Hello World")); RunContext runContext = runContextFactory.of(Map.of("filename", "file.txt", "content", "Hello World"));
Map<String, String> content = FilesService.inputFiles(runContext, Map.of("{{filename}}", "{{content}}")); Map<String, String> content = FilesService.inputFiles(runContext, Map.of("{{filename}}", "{{content}}"));
assertThat(content.get("file.txt"), is("Hello World")); assertThat(content.get("file.txt")).isEqualTo("Hello World");
} }
@Test @Test
void renderRawFile() throws Exception { void renderRawFile() throws Exception {
RunContext runContext = runContextFactory.of(Map.of("filename", "file.txt", "content", "Hello World")); RunContext runContext = runContextFactory.of(Map.of("filename", "file.txt", "content", "Hello World"));
Map<String, String> content = FilesService.inputFiles(runContext, Map.of("{{filename}}", "{% raw %}{{content}}{% endraw %}")); Map<String, String> content = FilesService.inputFiles(runContext, Map.of("{{filename}}", "{% raw %}{{content}}{% endraw %}"));
assertThat(content.get("file.txt"), is("{{content}}")); assertThat(content.get("file.txt")).isEqualTo("{{content}}");
} }
@Test @Test
@@ -48,7 +47,7 @@ class FilesServiceTest {
Map<String, String> files = FilesService.inputFiles(runContext, Map.of("file.txt", "content")); Map<String, String> files = FilesService.inputFiles(runContext, Map.of("file.txt", "content"));
Map<String, URI> outputs = FilesService.outputFiles(runContext, files.keySet().stream().toList()); Map<String, URI> outputs = FilesService.outputFiles(runContext, files.keySet().stream().toList());
assertThat(outputs.size(), is(1)); assertThat(outputs.size()).isEqualTo(1);
} }
@Test @Test
@@ -57,6 +56,6 @@ class FilesServiceTest {
Map<String, String> files = FilesService.inputFiles(runContext, Map.of("file.txt", "content")); Map<String, String> files = FilesService.inputFiles(runContext, Map.of("file.txt", "content"));
Map<String, URI> outputs = FilesService.outputFiles(runContext, List.of("*.{{extension}}")); Map<String, URI> outputs = FilesService.outputFiles(runContext, List.of("*.{{extension}}"));
assertThat(outputs.size(), is(1)); assertThat(outputs.size()).isEqualTo(1);
} }
} }

View File

@@ -20,8 +20,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@Singleton @Singleton
@@ -40,8 +39,8 @@ public class FlowConcurrencyCaseTest {
Execution execution1 = runnerUtils.runOneUntilRunning(null, "io.kestra.tests", "flow-concurrency-cancel", null, null, Duration.ofSeconds(30)); Execution execution1 = runnerUtils.runOneUntilRunning(null, "io.kestra.tests", "flow-concurrency-cancel", null, null, Duration.ofSeconds(30));
Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "flow-concurrency-cancel"); Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "flow-concurrency-cancel");
assertThat(execution1.getState().isRunning(), is(true)); assertThat(execution1.getState().isRunning()).isEqualTo(true);
assertThat(execution2.getState().getCurrent(), is(State.Type.CANCELLED)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.CANCELLED);
CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch1 = new CountDownLatch(1);
@@ -63,8 +62,8 @@ public class FlowConcurrencyCaseTest {
Execution execution1 = runnerUtils.runOneUntilRunning(null, "io.kestra.tests", "flow-concurrency-fail", null, null, Duration.ofSeconds(30)); Execution execution1 = runnerUtils.runOneUntilRunning(null, "io.kestra.tests", "flow-concurrency-fail", null, null, Duration.ofSeconds(30));
Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "flow-concurrency-fail"); Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "flow-concurrency-fail");
assertThat(execution1.getState().isRunning(), is(true)); assertThat(execution1.getState().isRunning()).isEqualTo(true);
assertThat(execution2.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.FAILED);
CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch1 = new CountDownLatch(1);
@@ -90,8 +89,8 @@ public class FlowConcurrencyCaseTest {
Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty()); Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty());
executionQueue.emit(execution2); executionQueue.emit(execution2);
assertThat(execution1.getState().isRunning(), is(true)); assertThat(execution1.getState().isRunning()).isEqualTo(true);
assertThat(execution2.getState().getCurrent(), is(State.Type.CREATED)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.CREATED);
var executionResult1 = new AtomicReference<Execution>(); var executionResult1 = new AtomicReference<Execution>();
var executionResult2 = new AtomicReference<Execution>(); var executionResult2 = new AtomicReference<Execution>();
@@ -124,11 +123,11 @@ public class FlowConcurrencyCaseTest {
assertTrue(latch3.await(1, TimeUnit.MINUTES)); assertTrue(latch3.await(1, TimeUnit.MINUTES));
receive.blockLast(); receive.blockLast();
assertThat(executionResult1.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(executionResult1.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(executionResult2.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(executionResult2.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(executionResult2.get().getState().getHistories().getFirst().getState(), is(State.Type.CREATED)); assertThat(executionResult2.get().getState().getHistories().getFirst().getState()).isEqualTo(State.Type.CREATED);
assertThat(executionResult2.get().getState().getHistories().get(1).getState(), is(State.Type.QUEUED)); assertThat(executionResult2.get().getState().getHistories().get(1).getState()).isEqualTo(State.Type.QUEUED);
assertThat(executionResult2.get().getState().getHistories().get(2).getState(), is(State.Type.RUNNING)); assertThat(executionResult2.get().getState().getHistories().get(2).getState()).isEqualTo(State.Type.RUNNING);
} }
public void flowConcurrencyQueuePause() throws TimeoutException, QueueException, InterruptedException { public void flowConcurrencyQueuePause() throws TimeoutException, QueueException, InterruptedException {
@@ -139,8 +138,8 @@ public class FlowConcurrencyCaseTest {
Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty()); Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty());
executionQueue.emit(execution2); executionQueue.emit(execution2);
assertThat(execution1.getState().isRunning(), is(true)); assertThat(execution1.getState().isRunning()).isEqualTo(true);
assertThat(execution2.getState().getCurrent(), is(State.Type.CREATED)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.CREATED);
var executionResult1 = new AtomicReference<Execution>(); var executionResult1 = new AtomicReference<Execution>();
var executionResult2 = new AtomicReference<Execution>(); var executionResult2 = new AtomicReference<Execution>();
@@ -173,11 +172,11 @@ public class FlowConcurrencyCaseTest {
assertTrue(latch3.await(1, TimeUnit.MINUTES)); assertTrue(latch3.await(1, TimeUnit.MINUTES));
receive.blockLast(); receive.blockLast();
assertThat(executionResult1.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(executionResult1.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(executionResult2.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(executionResult2.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(executionResult2.get().getState().getHistories().getFirst().getState(), is(State.Type.CREATED)); assertThat(executionResult2.get().getState().getHistories().getFirst().getState()).isEqualTo(State.Type.CREATED);
assertThat(executionResult2.get().getState().getHistories().get(1).getState(), is(State.Type.QUEUED)); assertThat(executionResult2.get().getState().getHistories().get(1).getState()).isEqualTo(State.Type.QUEUED);
assertThat(executionResult2.get().getState().getHistories().get(2).getState(), is(State.Type.RUNNING)); assertThat(executionResult2.get().getState().getHistories().get(2).getState()).isEqualTo(State.Type.RUNNING);
} }
public void flowConcurrencyCancelPause() throws TimeoutException, QueueException, InterruptedException { public void flowConcurrencyCancelPause() throws TimeoutException, QueueException, InterruptedException {
@@ -188,8 +187,8 @@ public class FlowConcurrencyCaseTest {
Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty()); Execution execution2 = Execution.newExecution(flow, null, null, Optional.empty());
executionQueue.emit(execution2); executionQueue.emit(execution2);
assertThat(execution1.getState().isRunning(), is(true)); assertThat(execution1.getState().isRunning()).isEqualTo(true);
assertThat(execution2.getState().getCurrent(), is(State.Type.CREATED)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.CREATED);
var executionResult1 = new AtomicReference<Execution>(); var executionResult1 = new AtomicReference<Execution>();
var executionResult2 = new AtomicReference<Execution>(); var executionResult2 = new AtomicReference<Execution>();
@@ -217,9 +216,9 @@ public class FlowConcurrencyCaseTest {
assertTrue(latch2.await(1, TimeUnit.MINUTES)); assertTrue(latch2.await(1, TimeUnit.MINUTES));
receive.blockLast(); receive.blockLast();
assertThat(executionResult1.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(executionResult1.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(executionResult2.get().getState().getCurrent(), is(State.Type.CANCELLED)); assertThat(executionResult2.get().getState().getCurrent()).isEqualTo(State.Type.CANCELLED);
assertThat(executionResult2.get().getState().getHistories().getFirst().getState(), is(State.Type.CREATED)); assertThat(executionResult2.get().getState().getHistories().getFirst().getState()).isEqualTo(State.Type.CREATED);
assertThat(executionResult2.get().getState().getHistories().get(1).getState(), is(State.Type.CANCELLED)); assertThat(executionResult2.get().getState().getHistories().get(1).getState()).isEqualTo(State.Type.CANCELLED);
} }
} }

View File

@@ -17,8 +17,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import jakarta.inject.Inject; import jakarta.inject.Inject;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@KestraTest @KestraTest
abstract public class FlowListenersTest { abstract public class FlowListenersTest {
@@ -52,15 +51,15 @@ abstract public class FlowListenersTest {
// initial state // initial state
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(0)); assertThat(count.get()).isEqualTo(0);
assertThat(flowListenersService.flows().size(), is(0)); assertThat(flowListenersService.flows().size()).isEqualTo(0);
}); });
// resend on startup done for kafka // resend on startup done for kafka
if (flowListenersService.getClass().getName().equals("io.kestra.ee.runner.kafka.KafkaFlowListeners")) { if (flowListenersService.getClass().getName().equals("io.kestra.ee.runner.kafka.KafkaFlowListeners")) {
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(0)); assertThat(count.get()).isEqualTo(0);
assertThat(flowListenersService.flows().size(), is(0)); assertThat(flowListenersService.flows().size()).isEqualTo(0);
}); });
} }
@@ -71,15 +70,15 @@ abstract public class FlowListenersTest {
flowRepository.create(GenericFlow.of(first)); flowRepository.create(GenericFlow.of(first));
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(1)); assertThat(count.get()).isEqualTo(1);
assertThat(flowListenersService.flows().size(), is(1)); assertThat(flowListenersService.flows().size()).isEqualTo(1);
}); });
// create the same id than first, no additional flows // create the same id than first, no additional flows
first = flowRepository.update(GenericFlow.of(firstUpdated), first); first = flowRepository.update(GenericFlow.of(firstUpdated), first);
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(1)); assertThat(count.get()).isEqualTo(1);
assertThat(flowListenersService.flows().size(), is(1)); assertThat(flowListenersService.flows().size()).isEqualTo(1);
//assertThat(flowListenersService.flows().getFirst().getFirst().getId(), is("test2")); //assertThat(flowListenersService.flows().getFirst().getFirst().getId(), is("test2"));
}); });
@@ -87,29 +86,29 @@ abstract public class FlowListenersTest {
// create a new one // create a new one
flowRepository.create(GenericFlow.of(second)); flowRepository.create(GenericFlow.of(second));
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(2)); assertThat(count.get()).isEqualTo(2);
assertThat(flowListenersService.flows().size(), is(2)); assertThat(flowListenersService.flows().size()).isEqualTo(2);
}); });
// delete first // delete first
FlowWithSource deleted = flowRepository.delete(first); FlowWithSource deleted = flowRepository.delete(first);
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(1)); assertThat(count.get()).isEqualTo(1);
assertThat(flowListenersService.flows().size(), is(1)); assertThat(flowListenersService.flows().size()).isEqualTo(1);
}); });
// restore must works // restore must works
flowRepository.create(GenericFlow.of(first)); flowRepository.create(GenericFlow.of(first));
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(2)); assertThat(count.get()).isEqualTo(2);
assertThat(flowListenersService.flows().size(), is(2)); assertThat(flowListenersService.flows().size()).isEqualTo(2);
}); });
FlowWithSource withTenant = first.toBuilder().tenantId("some-tenant").build(); FlowWithSource withTenant = first.toBuilder().tenantId("some-tenant").build();
flowRepository.create(GenericFlow.of(withTenant)); flowRepository.create(GenericFlow.of(withTenant));
wait(ref, () -> { wait(ref, () -> {
assertThat(count.get(), is(3)); assertThat(count.get()).isEqualTo(3);
assertThat(flowListenersService.flows().size(), is(3)); assertThat(flowListenersService.flows().size()).isEqualTo(3);
}); });
} }

View File

@@ -19,9 +19,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@Singleton @Singleton
@@ -57,29 +55,34 @@ public class FlowTriggerCaseTest {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", "trigger-flow"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", "trigger-flow");
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertTrue(countDownLatch.await(15, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(15, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(flowListener.get().getTaskRunList().size(), is(1)); assertThat(flowListener.get().getTaskRunList().size()).isEqualTo(1);
assertThat(flowListener.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(flowListener.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(flowListener.get().getTaskRunList().getFirst().getOutputs().get("value"), is("childs: from parents: " + execution.getId())); assertThat(flowListener.get().getTaskRunList().getFirst().getOutputs().get("value")).isEqualTo("childs: from parents: " + execution.getId());
assertThat(flowListener.get().getTrigger().getVariables().get("executionId"), is(execution.getId())); assertThat(flowListener.get().getTrigger().getVariables().get("executionId")).isEqualTo(execution.getId());
assertThat(flowListener.get().getTrigger().getVariables().get("namespace"), is("io.kestra.tests.trigger")); assertThat(flowListener.get().getTrigger().getVariables().get("namespace")).isEqualTo("io.kestra.tests.trigger");
assertThat(flowListener.get().getTrigger().getVariables().get("flowId"), is("trigger-flow")); assertThat(flowListener.get().getTrigger().getVariables().get("flowId")).isEqualTo("trigger-flow");
assertThat(flowListenerNoInput.get().getTaskRunList().size(), is(1)); assertThat(flowListenerNoInput.get().getTaskRunList().size()).isEqualTo(1);
assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("executionId"), is(execution.getId())); assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("executionId")).isEqualTo(execution.getId());
assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("namespace"), is("io.kestra.tests.trigger")); assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("namespace")).isEqualTo("io.kestra.tests.trigger");
assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("flowId"), is("trigger-flow")); assertThat(flowListenerNoInput.get().getTrigger().getVariables().get("flowId")).isEqualTo("trigger-flow");
assertThat(flowListenerNoInput.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(flowListenerNoInput.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(flowListenerNamespace.get().getTaskRunList().size(), is(1)); assertThat(flowListenerNamespace.get().getTaskRunList().size()).isEqualTo(1);
assertThat(flowListenerNamespace.get().getTrigger().getVariables().get("namespace"), is("io.kestra.tests.trigger")); assertThat(flowListenerNamespace.get().getTrigger().getVariables().get("namespace")).isEqualTo("io.kestra.tests.trigger");
// it will be triggered for 'trigger-flow' or any of the 'trigger-flow-listener*', so we only assert that it's one of them // it will be triggered for 'trigger-flow' or any of the 'trigger-flow-listener*', so we only assert that it's one of them
assertThat(flowListenerNamespace.get().getTrigger().getVariables().get("flowId"), anyOf(is("trigger-flow"), is("trigger-flow-listener-no-inputs"), is("trigger-flow-listener"))); assertThat(flowListenerNamespace.get().getTrigger().getVariables().get("flowId"))
.satisfiesAnyOf(
arg -> assertThat(arg).isEqualTo("trigger-flow"),
arg -> assertThat(arg).isEqualTo("trigger-flow-listener-no-inputs"),
arg -> assertThat(arg).isEqualTo("trigger-flow-listener")
);
} }
public void triggerWithPause() throws InterruptedException, TimeoutException, QueueException { public void triggerWithPause() throws InterruptedException, TimeoutException, QueueException {
@@ -96,16 +99,16 @@ public class FlowTriggerCaseTest {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.pause", "trigger-flow-with-pause"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.pause", "trigger-flow-with-pause");
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertTrue(countDownLatch.await(15, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(15, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(flowListeners.size(), is(4)); assertThat(flowListeners.size()).isEqualTo(4);
assertThat(flowListeners.get(0).getOutputs().get("status"), is("RUNNING")); assertThat(flowListeners.get(0).getOutputs().get("status")).isEqualTo("RUNNING");
assertThat(flowListeners.get(1).getOutputs().get("status"), is("PAUSED")); assertThat(flowListeners.get(1).getOutputs().get("status")).isEqualTo("PAUSED");
assertThat(flowListeners.get(2).getOutputs().get("status"), is("RUNNING")); assertThat(flowListeners.get(2).getOutputs().get("status")).isEqualTo("RUNNING");
assertThat(flowListeners.get(3).getOutputs().get("status"), is("SUCCESS")); assertThat(flowListeners.get(3).getOutputs().get("status")).isEqualTo("SUCCESS");
} }
} }

View File

@@ -34,8 +34,7 @@ import java.time.LocalTime;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
@@ -111,7 +110,7 @@ public class InputsTest {
HashMap<String, Object> inputs = new HashMap<>(InputsTest.inputs); HashMap<String, Object> inputs = new HashMap<>(InputsTest.inputs);
inputs.put("string", null); inputs.put("string", null);
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(inputs)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(inputs));
assertThat(e.getMessage(), containsString("Invalid input for `string`, missing required input, but received `null`")); assertThat(e.getMessage()).contains("Invalid input for `string`, missing required input, but received `null`");
} }
@Test @Test
@@ -120,8 +119,8 @@ public class InputsTest {
HashMap<String, Object> inputsWithMissingOptionalInput = new HashMap<>(inputs); HashMap<String, Object> inputsWithMissingOptionalInput = new HashMap<>(inputs);
inputsWithMissingOptionalInput.remove("bool"); inputsWithMissingOptionalInput.remove("bool");
assertThat(typedInputs(inputsWithMissingOptionalInput).containsKey("bool"), is(true)); assertThat(typedInputs(inputsWithMissingOptionalInput).containsKey("bool")).isEqualTo(true);
assertThat(typedInputs(inputsWithMissingOptionalInput).get("bool"), nullValue()); assertThat(typedInputs(inputsWithMissingOptionalInput).get("bool")).isNull();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -130,39 +129,36 @@ public class InputsTest {
void allValidInputs() throws URISyntaxException, IOException { void allValidInputs() throws URISyntaxException, IOException {
Map<String, Object> typeds = typedInputs(inputs); Map<String, Object> typeds = typedInputs(inputs);
assertThat(typeds.get("string"), is("myString")); assertThat(typeds.get("string")).isEqualTo("myString");
assertThat(typeds.get("int"), is(42)); assertThat(typeds.get("int")).isEqualTo(42);
assertThat(typeds.get("float"), is(42.42F)); assertThat(typeds.get("float")).isEqualTo(42.42F);
assertThat(typeds.get("bool"), is(false)); assertThat(typeds.get("bool")).isEqualTo(false);
assertThat(typeds.get("instant"), is(Instant.parse("2019-10-06T18:27:49Z"))); assertThat(typeds.get("instant")).isEqualTo(Instant.parse("2019-10-06T18:27:49Z"));
assertThat(typeds.get("instantDefaults"), is(Instant.parse("2013-08-09T14:19:00Z"))); assertThat(typeds.get("instantDefaults")).isEqualTo(Instant.parse("2013-08-09T14:19:00Z"));
assertThat(typeds.get("date"), is(LocalDate.parse("2019-10-06"))); assertThat(typeds.get("date")).isEqualTo(LocalDate.parse("2019-10-06"));
assertThat(typeds.get("time"), is(LocalTime.parse("18:27:49"))); assertThat(typeds.get("time")).isEqualTo(LocalTime.parse("18:27:49"));
assertThat(typeds.get("duration"), is(Duration.parse("PT5M6S"))); assertThat(typeds.get("duration")).isEqualTo(Duration.parse("PT5M6S"));
assertThat((URI) typeds.get("file"), is(new URI("kestra:///io/kestra/tests/inputs/executions/test/inputs/file/application-test.yml"))); assertThat((URI) typeds.get("file")).isEqualTo(new URI("kestra:///io/kestra/tests/inputs/executions/test/inputs/file/application-test.yml"));
assertThat( assertThat(CharStreams.toString(new InputStreamReader(storageInterface.get(null, null, (URI) typeds.get("file"))))).isEqualTo(CharStreams.toString(new InputStreamReader(new FileInputStream((String) inputs.get("file")))));
CharStreams.toString(new InputStreamReader(storageInterface.get(null, null, (URI) typeds.get("file")))), assertThat(typeds.get("json")).isEqualTo(Map.of("a", "b"));
is(CharStreams.toString(new InputStreamReader(new FileInputStream((String) inputs.get("file"))))) assertThat(typeds.get("uri")).isEqualTo("https://www.google.com");
); assertThat(((Map<String, Object>) typeds.get("nested")).get("string")).isEqualTo("a string");
assertThat(typeds.get("json"), is(Map.of("a", "b"))); assertThat(((Map<String, Object>) typeds.get("nested")).get("bool")).isEqualTo(true);
assertThat(typeds.get("uri"), is("https://www.google.com")); assertThat(((Map<String, Object>) ((Map<String, Object>) typeds.get("nested")).get("more")).get("int")).isEqualTo(123);
assertThat(((Map<String, Object>)typeds.get("nested")).get("string"), is("a string")); assertThat(typeds.get("validatedString")).isEqualTo("A123");
assertThat(((Map<String, Object>)typeds.get("nested")).get("bool"), is(true)); assertThat(typeds.get("validatedInt")).isEqualTo(12);
assertThat(((Map<String, Object>)((Map<String, Object>)typeds.get("nested")).get("more")).get("int"), is(123)); assertThat(typeds.get("validatedDate")).isEqualTo(LocalDate.parse("2023-01-02"));
assertThat(typeds.get("validatedString"), is("A123")); assertThat(typeds.get("validatedDateTime")).isEqualTo(Instant.parse("2023-01-01T00:00:10Z"));
assertThat(typeds.get("validatedInt"), is(12)); assertThat(typeds.get("validatedDuration")).isEqualTo(Duration.parse("PT15S"));
assertThat(typeds.get("validatedDate"), is(LocalDate.parse("2023-01-02"))); assertThat(typeds.get("validatedFloat")).isEqualTo(0.42F);
assertThat(typeds.get("validatedDateTime"), is(Instant.parse("2023-01-01T00:00:10Z"))); assertThat(typeds.get("validatedTime")).isEqualTo(LocalTime.parse("11:27:49"));
assertThat(typeds.get("validatedDuration"), is(Duration.parse("PT15S"))); assertThat(typeds.get("secret")).isNotEqualTo("secret"); // secret inputs are encrypted
assertThat(typeds.get("validatedFloat"), is(0.42F)); assertThat(typeds.get("array")).isInstanceOf(List.class);
assertThat(typeds.get("validatedTime"), is(LocalTime.parse("11:27:49"))); assertThat((List<Integer>) typeds.get("array")).hasSize(3);
assertThat(typeds.get("secret"), not("secret")); // secret inputs are encrypted assertThat((List<Integer>) typeds.get("array")).isEqualTo(List.of(1, 2, 3));
assertThat(typeds.get("array"), instanceOf(List.class)); assertThat(typeds.get("yaml")).isEqualTo(Map.of(
assertThat((List<String>)typeds.get("array"), hasSize(3));
assertThat((List<String>)typeds.get("array"), contains(1, 2, 3));
assertThat(typeds.get("yaml"), is(Map.of(
"some", "property", "some", "property",
"alist", List.of("of", "values")))); "alist", List.of("of", "values")));
} }
@Test @Test
@@ -173,11 +169,11 @@ public class InputsTest {
typeds.put("float", 42.42F); typeds.put("float", 42.42F);
typeds.put("bool", false); typeds.put("bool", false);
assertThat(typeds.get("string"), is("myString")); assertThat(typeds.get("string")).isEqualTo("myString");
assertThat(typeds.get("enum"), is("ENUM_VALUE")); assertThat(typeds.get("enum")).isEqualTo("ENUM_VALUE");
assertThat(typeds.get("int"), is(42)); assertThat(typeds.get("int")).isEqualTo(42);
assertThat(typeds.get("float"), is(42.42F)); assertThat(typeds.get("float")).isEqualTo(42.42F);
assertThat(typeds.get("bool"), is(false)); assertThat(typeds.get("bool")).isEqualTo(false);
} }
@Test @Test
@@ -191,22 +187,13 @@ public class InputsTest {
(flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs) (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs)
); );
assertThat(execution.getTaskRunList(), hasSize(14)); assertThat(execution.getTaskRunList()).hasSize(14);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat( assertThat((String) execution.findTaskRunsByTaskId("file").getFirst().getOutputs().get("value")).matches("kestra:///io/kestra/tests/inputs/executions/.*/inputs/file/application-test.yml");
(String) execution.findTaskRunsByTaskId("file").getFirst().getOutputs().get("value"),
matchesRegex("kestra:///io/kestra/tests/inputs/executions/.*/inputs/file/application-test.yml")
);
// secret inputs are decrypted to be used as task properties // secret inputs are decrypted to be used as task properties
assertThat( assertThat((String) execution.findTaskRunsByTaskId("secret").getFirst().getOutputs().get("value")).isEqualTo("secret");
(String) execution.findTaskRunsByTaskId("secret").getFirst().getOutputs().get("value"),
is("secret")
);
// null inputs are serialized // null inputs are serialized
assertThat( assertThat((String) execution.findTaskRunsByTaskId("optional").getFirst().getOutputs().get("value")).isEmpty();
(String) execution.findTaskRunsByTaskId("optional").getFirst().getOutputs().get("value"),
emptyString()
);
} }
@Test @Test
@@ -217,7 +204,7 @@ public class InputsTest {
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map));
assertThat(e.getMessage(), containsString("Invalid input for `validatedString`, it must match the pattern")); assertThat(e.getMessage()).contains("Invalid input for `validatedString`, it must match the pattern");
} }
@Test @Test
@@ -226,14 +213,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedInt", "9"); mapMin.put("validatedInt", "9");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedInt`, it must be more than `10`, but received `9`")); assertThat(e.getMessage()).contains("Invalid input for `validatedInt`, it must be more than `10`, but received `9`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedInt", "21"); mapMax.put("validatedInt", "21");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedInt`, it must be less than `20`, but received `21`")); assertThat(e.getMessage()).contains("Invalid input for `validatedInt`, it must be less than `20`, but received `21`");
} }
@Test @Test
@@ -242,14 +229,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedDate", "2022-01-01"); mapMin.put("validatedDate", "2022-01-01");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDate`, it must be after `2023-01-01`, but received `2022-01-01`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDate`, it must be after `2023-01-01`, but received `2022-01-01`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedDate", "2024-01-01"); mapMax.put("validatedDate", "2024-01-01");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDate`, it must be before `2023-12-31`, but received `2024-01-01`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDate`, it must be before `2023-12-31`, but received `2024-01-01`");
} }
@Test @Test
@@ -258,14 +245,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedDateTime", "2022-01-01T00:00:00Z"); mapMin.put("validatedDateTime", "2022-01-01T00:00:00Z");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDateTime`, it must be after `2023-01-01T00:00:00Z`, but received `2022-01-01T00:00:00Z`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDateTime`, it must be after `2023-01-01T00:00:00Z`, but received `2022-01-01T00:00:00Z`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedDateTime", "2024-01-01T00:00:00Z"); mapMax.put("validatedDateTime", "2024-01-01T00:00:00Z");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDateTime`, it must be before `2023-12-31T23:59:59Z`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDateTime`, it must be before `2023-12-31T23:59:59Z`");
} }
@Test @Test
@@ -274,14 +261,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedDuration", "PT1S"); mapMin.put("validatedDuration", "PT1S");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDuration`, It must be more than `PT10S`, but received `PT1S`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDuration`, It must be more than `PT10S`, but received `PT1S`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedDuration", "PT30S"); mapMax.put("validatedDuration", "PT30S");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedDuration`, It must be less than `PT20S`, but received `PT30S`")); assertThat(e.getMessage()).contains("Invalid input for `validatedDuration`, It must be less than `PT20S`, but received `PT30S`");
} }
@Test @Test
@@ -290,14 +277,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedFloat", "0.01"); mapMin.put("validatedFloat", "0.01");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedFloat`, it must be more than `0.1`, but received `0.01`")); assertThat(e.getMessage()).contains("Invalid input for `validatedFloat`, it must be more than `0.1`, but received `0.01`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedFloat", "1.01"); mapMax.put("validatedFloat", "1.01");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedFloat`, it must be less than `0.5`, but received `1.01`")); assertThat(e.getMessage()).contains("Invalid input for `validatedFloat`, it must be less than `0.5`, but received `1.01`");
} }
@Test @Test
@@ -306,14 +293,14 @@ public class InputsTest {
HashMap<String, Object> mapMin = new HashMap<>(inputs); HashMap<String, Object> mapMin = new HashMap<>(inputs);
mapMin.put("validatedTime", "00:00:01"); mapMin.put("validatedTime", "00:00:01");
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMin));
assertThat(e.getMessage(), containsString("Invalid input for `validatedTime`, it must be after `01:00`, but received `00:00:01`")); assertThat(e.getMessage()).contains("Invalid input for `validatedTime`, it must be after `01:00`, but received `00:00:01`");
HashMap<String, Object> mapMax = new HashMap<>(inputs); HashMap<String, Object> mapMax = new HashMap<>(inputs);
mapMax.put("validatedTime", "14:00:00"); mapMax.put("validatedTime", "14:00:00");
e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax)); e = assertThrows(ConstraintViolationException.class, () -> typedInputs(mapMax));
assertThat(e.getMessage(), containsString("Invalid input for `validatedTime`, it must be before `11:59:59`, but received `14:00:00`")); assertThat(e.getMessage()).contains("Invalid input for `validatedTime`, it must be before `11:59:59`, but received `14:00:00`");
} }
@Test @Test
@@ -324,7 +311,7 @@ public class InputsTest {
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map));
assertThat(e.getMessage(), containsString("Invalid input for `uri`, Expected `URI` but received `http:/bla`, but received `http:/bla`")); assertThat(e.getMessage()).contains("Invalid input for `uri`, Expected `URI` but received `http:/bla`, but received `http:/bla`");
} }
@Test @Test
@@ -335,7 +322,7 @@ public class InputsTest {
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map));
assertThat(e.getMessage(), is("enum: Invalid input for `enum`, it must match the values `[ENUM_VALUE, OTHER_ONE]`, but received `INVALID`")); assertThat(e.getMessage()).isEqualTo("enum: Invalid input for `enum`, it must match the values `[ENUM_VALUE, OTHER_ONE]`, but received `INVALID`");
} }
@Test @Test
@@ -346,7 +333,7 @@ public class InputsTest {
ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map)); ConstraintViolationException e = assertThrows(ConstraintViolationException.class, () -> typedInputs(map));
assertThat(e.getMessage(), containsString("Invalid input for `array`, Unable to parse array element as `INT` on `s1`, but received `[\"s1\", \"s2\"]`")); assertThat(e.getMessage()).contains("Invalid input for `array`, Unable to parse array element as `INT` on `s1`, but received `[\"s1\", \"s2\"]`");
} }
@Test @Test
@@ -357,8 +344,8 @@ public class InputsTest {
Map<String, Object> typeds = typedInputs(map); Map<String, Object> typeds = typedInputs(map);
assertThat(typeds.get("json"), instanceOf(Map.class)); assertThat(typeds.get("json")).isInstanceOf(Map.class);
assertThat(((Map<?, ?>) typeds.get("json")).size(), is(0)); assertThat(((Map<?, ?>) typeds.get("json")).size()).isEqualTo(0);
} }
@Test @Test
@@ -375,12 +362,12 @@ public class InputsTest {
(flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, map) (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, map)
); );
assertThat(execution.getTaskRunList(), hasSize(14)); assertThat(execution.getTaskRunList()).hasSize(14);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getInputs().get("json"), instanceOf(Map.class)); assertThat(execution.getInputs().get("json")).isInstanceOf(Map.class);
assertThat(((Map<?, ?>) execution.getInputs().get("json")).size(), is(0)); assertThat(((Map<?, ?>) execution.getInputs().get("json")).size()).isEqualTo(0);
assertThat((String) execution.findTaskRunsByTaskId("jsonOutput").getFirst().getOutputs().get("value"), is("{}")); assertThat((String) execution.findTaskRunsByTaskId("jsonOutput").getFirst().getOutputs().get("value")).isEqualTo("{}");
} }
@RetryingTest(5) // it can happen that a log from another execution arrives first, so we enable retry @RetryingTest(5) // it can happen that a log from another execution arrives first, so we enable retry
@@ -394,11 +381,11 @@ public class InputsTest {
"input-log-secret" "input-log-secret"
); );
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
var logEntry = receive.blockLast(); var logEntry = receive.blockLast();
assertThat(logEntry, notNullValue()); assertThat(logEntry).isNotNull();
assertThat(logEntry.getMessage(), is("This is my secret: ********")); assertThat(logEntry.getMessage()).isEqualTo("This is my secret: ********");
} }
} }

View File

@@ -15,9 +15,7 @@ import java.net.URISyntaxException;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
class ListenersTest { class ListenersTest {
@@ -47,9 +45,9 @@ class ListenersTest {
(f, e) -> ImmutableMap.of("string", "OK") (f, e) -> ImmutableMap.of("string", "OK")
); );
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("ok")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("ok");
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat((String) execution.getTaskRunList().get(2).getOutputs().get("value"), containsString("flowId=listeners")); assertThat((String) execution.getTaskRunList().get(2).getOutputs().get("value")).contains("flowId=listeners");
} }
@Test @Test
@@ -62,9 +60,9 @@ class ListenersTest {
(f, e) -> ImmutableMap.of("string", "KO") (f, e) -> ImmutableMap.of("string", "KO")
); );
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("ko")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("ko");
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getTaskRunList().get(2).getTaskId(), is("execution-failed-listener")); assertThat(execution.getTaskRunList().get(2).getTaskId()).isEqualTo("execution-failed-listener");
} }
@Test @Test
@@ -77,10 +75,10 @@ class ListenersTest {
(f, e) -> ImmutableMap.of("string", "execution") (f, e) -> ImmutableMap.of("string", "execution")
); );
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("parent-seq")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("parent-seq");
assertThat(execution.getTaskRunList().get(2).getTaskId(), is("execution-success-listener")); assertThat(execution.getTaskRunList().get(2).getTaskId()).isEqualTo("execution-success-listener");
assertThat((String) execution.getTaskRunList().get(2).getOutputs().get("value"), containsString(execution.getId())); assertThat((String) execution.getTaskRunList().get(2).getOutputs().get("value")).contains(execution.getId());
} }
@Test @Test
@@ -91,9 +89,9 @@ class ListenersTest {
"listeners-multiple" "listeners-multiple"
); );
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("l1")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("l1");
assertThat(execution.getTaskRunList().get(2).getTaskId(), is("l2")); assertThat(execution.getTaskRunList().get(2).getTaskId()).isEqualTo("l2");
} }
@Test @Test
@@ -104,10 +102,10 @@ class ListenersTest {
"listeners-failed" "listeners-failed"
); );
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList().size(), is(2)); assertThat(execution.getTaskRunList().size()).isEqualTo(2);
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("ko")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("ko");
assertThat(execution.getTaskRunList().get(1).getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().get(1).getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
@Test @Test
@@ -118,11 +116,11 @@ class ListenersTest {
"listeners-multiple-failed" "listeners-multiple-failed"
); );
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList().size(), is(3)); assertThat(execution.getTaskRunList().size()).isEqualTo(3);
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("ko")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("ko");
assertThat(execution.getTaskRunList().get(1).getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getTaskRunList().get(1).getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList().get(2).getTaskId(), is("l2")); assertThat(execution.getTaskRunList().get(2).getTaskId()).isEqualTo("l2");
assertThat(execution.getTaskRunList().get(2).getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getTaskRunList().get(2).getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
} }

View File

@@ -13,9 +13,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
class LocalWorkingDirTest { class LocalWorkingDirTest {
@@ -30,7 +28,7 @@ class LocalWorkingDirTest {
@Test @Test
void shouldReturnTheSameWorkingDirPath() { void shouldReturnTheSameWorkingDirPath() {
LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create()); LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create());
assertThat(workingDirectory.path(), is(workingDirectory.path())); assertThat(workingDirectory.path()).isEqualTo(workingDirectory.path());
} }
@Test @Test
@@ -38,12 +36,12 @@ class LocalWorkingDirTest {
LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create()); LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create());
Path path = workingDirectory.resolve(Path.of("file.txt")); Path path = workingDirectory.resolve(Path.of("file.txt"));
assertThat(path.toString(), is(workingDirectory.path() + "/file.txt")); assertThat(path.toString()).isEqualTo(workingDirectory.path() + "/file.txt");
path = workingDirectory.resolve(Path.of("subdir/file.txt")); path = workingDirectory.resolve(Path.of("subdir/file.txt"));
assertThat(path.toString(), is(workingDirectory.path() + "/subdir/file.txt")); assertThat(path.toString()).isEqualTo(workingDirectory.path() + "/subdir/file.txt");
assertThat(workingDirectory.resolve(null), is(workingDirectory.path())); assertThat(workingDirectory.resolve(null)).isEqualTo(workingDirectory.path());
assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("/etc/passwd"))); assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("/etc/passwd")));
assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("../../etc/passwd"))); assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("../../etc/passwd")));
assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("subdir/../../../etc/passwd"))); assertThrows(IllegalArgumentException.class, () -> workingDirectory.resolve(Path.of("subdir/../../../etc/passwd")));
@@ -54,8 +52,8 @@ class LocalWorkingDirTest {
String workingDirId = IdUtils.create(); String workingDirId = IdUtils.create();
TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId)); TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId));
Path tempFile = workingDirectory.createTempFile(); Path tempFile = workingDirectory.createTempFile();
assertThat(tempFile.toFile().getAbsolutePath().startsWith("/tmp/sub/dir/tmp/"), is(true)); assertThat(tempFile.toFile().getAbsolutePath().startsWith("/tmp/sub/dir/tmp/")).isEqualTo(true);
assertThat(workingDirectory.getAllCreatedTempFiles().size(), is(1)); assertThat(workingDirectory.getAllCreatedTempFiles().size()).isEqualTo(1);
} }
@Test @Test
@@ -64,9 +62,9 @@ class LocalWorkingDirTest {
TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId)); TestWorkingDir workingDirectory = new TestWorkingDir(workingDirId, new LocalWorkingDir(Path.of("/tmp/sub/dir/tmp/"), workingDirId));
Path path = workingDirectory.createFile("folder/file.txt"); Path path = workingDirectory.createFile("folder/file.txt");
assertThat(path.toFile().getAbsolutePath().startsWith("/tmp/sub/dir/tmp/"), is(true)); assertThat(path.toFile().getAbsolutePath().startsWith("/tmp/sub/dir/tmp/")).isEqualTo(true);
assertThat(path.toFile().getAbsolutePath().endsWith("/folder/file.txt"), is(true)); assertThat(path.toFile().getAbsolutePath().endsWith("/folder/file.txt")).isEqualTo(true);
assertThat(workingDirectory.getAllCreatedFiles().size(), is(1)); assertThat(workingDirectory.getAllCreatedFiles().size()).isEqualTo(1);
} }
@Test @Test
@@ -93,13 +91,13 @@ class LocalWorkingDirTest {
// When - Then // When - Then
// glob // glob
assertThat(workingDir.findAllFilesMatching(List.of("glob:**/*.*")).size(), is(5)); assertThat(workingDir.findAllFilesMatching(List.of("glob:**/*.*")).size()).isEqualTo(5);
// pattern // pattern
assertThat(workingDir.findAllFilesMatching(List.of("*.*", "**/*.*")).size(), is(5)); assertThat(workingDir.findAllFilesMatching(List.of("*.*", "**/*.*")).size()).isEqualTo(5);
// duplicate pattern // duplicate pattern
assertThat(workingDir.findAllFilesMatching(List.of("*.*", "**/*.*", "**/*.*")).size(), is(5)); assertThat(workingDir.findAllFilesMatching(List.of("*.*", "**/*.*", "**/*.*")).size()).isEqualTo(5);
// regex // regex
assertThat(workingDir.findAllFilesMatching(List.of("regex:.*\\.tmp", "*.txt", "**/*.txt")).size(), is(5)); assertThat(workingDir.findAllFilesMatching(List.of("regex:.*\\.tmp", "*.txt", "**/*.txt")).size()).isEqualTo(5);
} }
@Test @Test
@@ -113,14 +111,14 @@ class LocalWorkingDirTest {
workingDir.cleanup(); workingDir.cleanup();
// Then // Then
assertThat(file.toFile().exists(), is(false)); assertThat(file.toFile().exists()).isEqualTo(false);
assertThat(firtPath.toFile().exists(), is(false)); assertThat(firtPath.toFile().exists()).isEqualTo(false);
// When // When
Path secondPath = workingDir.path(true); Path secondPath = workingDir.path(true);
// Then // Then
assertThat(secondPath.toFile().exists(), is(true)); assertThat(secondPath.toFile().exists()).isEqualTo(true);
assertThat(firtPath, equalTo(secondPath)); assertThat(firtPath).isEqualTo(secondPath);
} }
@Test @Test
@@ -130,15 +128,15 @@ class LocalWorkingDirTest {
Path file = workingDir.createFile("test.txt", new ByteArrayInputStream("First file".getBytes(StandardCharsets.UTF_8))); Path file = workingDir.createFile("test.txt", new ByteArrayInputStream("First file".getBytes(StandardCharsets.UTF_8)));
assertThrows(FileAlreadyExistsException.class, () -> workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.FAIL)); assertThrows(FileAlreadyExistsException.class, () -> workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.FAIL));
assertThat(Files.readAllLines(file, StandardCharsets.UTF_8), is(List.of("First file"))); assertThat(Files.readAllLines(file, StandardCharsets.UTF_8)).isEqualTo(List.of("First file"));
workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.IGNORE); workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.IGNORE);
assertThat(Files.readAllLines(file, StandardCharsets.UTF_8), is(List.of("First file"))); assertThat(Files.readAllLines(file, StandardCharsets.UTF_8)).isEqualTo(List.of("First file"));
workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.WARN); workingDir.putFile(file, new ByteArrayInputStream("Hello world".getBytes(StandardCharsets.UTF_8)), FileExistComportment.WARN);
assertThat(Files.readAllLines(file, StandardCharsets.UTF_8), is(List.of("First file"))); assertThat(Files.readAllLines(file, StandardCharsets.UTF_8)).isEqualTo(List.of("First file"));
workingDir.putFile(file, new ByteArrayInputStream("New file".getBytes(StandardCharsets.UTF_8)), FileExistComportment.OVERWRITE); workingDir.putFile(file, new ByteArrayInputStream("New file".getBytes(StandardCharsets.UTF_8)), FileExistComportment.OVERWRITE);
assertThat(Files.readAllLines(file, StandardCharsets.UTF_8), is(List.of("New file"))); assertThat(Files.readAllLines(file, StandardCharsets.UTF_8)).isEqualTo(List.of("New file"));
} }
} }

View File

@@ -15,8 +15,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
public class LogToFileTest { public class LogToFileTest {
@@ -26,18 +25,18 @@ public class LogToFileTest {
@Test @Test
@ExecuteFlow("flows/valids/log-to-file.yaml") @ExecuteFlow("flows/valids/log-to-file.yaml")
void task(Execution execution) throws Exception { void task(Execution execution) throws Exception {
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
TaskRun taskRun = execution.getTaskRunList().getFirst(); TaskRun taskRun = execution.getTaskRunList().getFirst();
assertThat(taskRun.getAttempts(), hasSize(1)); assertThat(taskRun.getAttempts()).hasSize(1);
TaskRunAttempt attempt = taskRun.getAttempts().getFirst(); TaskRunAttempt attempt = taskRun.getAttempts().getFirst();
assertThat(attempt.getLogFile(), notNullValue()); assertThat(attempt.getLogFile()).isNotNull();
InputStream inputStream = storage.get(null, "io.kestra.tests", attempt.getLogFile()); InputStream inputStream = storage.get(null, "io.kestra.tests", attempt.getLogFile());
List<String> strings = IOUtils.readLines(inputStream, StandardCharsets.UTF_8); List<String> strings = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
assertThat(strings, notNullValue()); assertThat(strings).isNotNull();
assertThat(strings.size(), is(1)); assertThat(strings.size()).isEqualTo(1);
assertThat(strings.getFirst(), containsString("INFO")); assertThat(strings.getFirst()).contains("INFO");
assertThat(strings.getFirst(), containsString("Hello World!")); assertThat(strings.getFirst()).contains("Hello World!");
} }
} }

View File

@@ -24,8 +24,7 @@ import jakarta.inject.Named;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@Singleton @Singleton
@@ -63,23 +62,23 @@ public class MultipleConditionTriggerCaseTest {
// first one // first one
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger",
"trigger-multiplecondition-flow-a", Duration.ofSeconds(60)); "trigger-multiplecondition-flow-a", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// wait a little to be sure that the trigger is not launching execution // wait a little to be sure that the trigger is not launching execution
Thread.sleep(1000); Thread.sleep(1000);
assertThat(ended.size(), is(1)); assertThat(ended.size()).isEqualTo(1);
// second one // second one
execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", execution = runnerUtils.runOne(null, "io.kestra.tests.trigger",
"trigger-multiplecondition-flow-b", Duration.ofSeconds(60)); "trigger-multiplecondition-flow-b", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// trigger is done // trigger is done
assertTrue(countDownLatch.await(10, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(10, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(ended.size(), is(3)); assertThat(ended.size()).isEqualTo(3);
Flow flow = flowRepository.findById(null, "io.kestra.tests.trigger", Flow flow = flowRepository.findById(null, "io.kestra.tests.trigger",
"trigger-multiplecondition-listener").orElseThrow(); "trigger-multiplecondition-listener").orElseThrow();
@@ -90,15 +89,12 @@ public class MultipleConditionTriggerCaseTest {
.map(Map.Entry::getValue) .map(Map.Entry::getValue)
.orElseThrow(); .orElseThrow();
assertThat(triggerExecution.getTaskRunList().size(), is(1)); assertThat(triggerExecution.getTaskRunList().size()).isEqualTo(1);
assertThat(triggerExecution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(triggerExecution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(triggerExecution.getTrigger().getVariables().get("executionId"), assertThat(triggerExecution.getTrigger().getVariables().get("executionId")).isEqualTo(execution.getId());
is(execution.getId())); assertThat(triggerExecution.getTrigger().getVariables().get("namespace")).isEqualTo("io.kestra.tests.trigger");
assertThat(triggerExecution.getTrigger().getVariables().get("namespace"), assertThat(triggerExecution.getTrigger().getVariables().get("flowId")).isEqualTo("trigger-multiplecondition-flow-b");
is("io.kestra.tests.trigger"));
assertThat(triggerExecution.getTrigger().getVariables().get("flowId"),
is("trigger-multiplecondition-flow-b"));
} }
public void failed() throws InterruptedException, TimeoutException, QueueException { public void failed() throws InterruptedException, TimeoutException, QueueException {
@@ -116,24 +112,24 @@ public class MultipleConditionTriggerCaseTest {
// first one // first one
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger",
"trigger-multiplecondition-flow-c", Duration.ofSeconds(60)); "trigger-multiplecondition-flow-c", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
// wait a little to be sure that the trigger is not launching execution // wait a little to be sure that the trigger is not launching execution
Thread.sleep(1000); Thread.sleep(1000);
assertThat(listener.get(), nullValue()); assertThat(listener.get()).isNull();
// second one // second one
execution = runnerUtils.runOne(null, "io.kestra.tests.trigger", execution = runnerUtils.runOne(null, "io.kestra.tests.trigger",
"trigger-multiplecondition-flow-d", Duration.ofSeconds(60)); "trigger-multiplecondition-flow-d", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// trigger was not done // trigger was not done
assertTrue(countDownLatch.await(10, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(10, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(listener.get(), notNullValue()); assertThat(listener.get()).isNotNull();
assertThat(listener.get().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(listener.get().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
public void flowTriggerPreconditions() public void flowTriggerPreconditions()
@@ -153,29 +149,29 @@ public class MultipleConditionTriggerCaseTest {
// flowA // flowA
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions", Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions",
"flow-trigger-preconditions-flow-a", Duration.ofSeconds(60)); "flow-trigger-preconditions-flow-a", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// flowB: we trigger it two times, as flow-trigger-flow-preconditions-flow-listen is configured with resetOnSuccess: false it should be triggered two times // flowB: we trigger it two times, as flow-trigger-flow-preconditions-flow-listen is configured with resetOnSuccess: false it should be triggered two times
execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions", execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions",
"flow-trigger-preconditions-flow-a", Duration.ofSeconds(60)); "flow-trigger-preconditions-flow-a", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions", execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions",
"flow-trigger-preconditions-flow-b", Duration.ofSeconds(60)); "flow-trigger-preconditions-flow-b", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// trigger is done // trigger is done
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(1, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(flowTrigger.get(), notNullValue()); assertThat(flowTrigger.get()).isNotNull();
Execution triggerExecution = flowTrigger.get(); Execution triggerExecution = flowTrigger.get();
assertThat(triggerExecution.getTaskRunList().size(), is(1)); assertThat(triggerExecution.getTaskRunList().size()).isEqualTo(1);
assertThat(triggerExecution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(triggerExecution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(triggerExecution.getTrigger().getVariables().get("outputs"), notNullValue()); assertThat(triggerExecution.getTrigger().getVariables().get("outputs")).isNotNull();
assertThat((Map<String, Object>) triggerExecution.getTrigger().getVariables().get("outputs"), hasEntry("some", "value")); assertThat((Map<String, Object>) triggerExecution.getTrigger().getVariables().get("outputs")).containsEntry("some", "value");
} }
public void flowTriggerPreconditionsMergeOutputs() throws QueueException, TimeoutException, InterruptedException { public void flowTriggerPreconditionsMergeOutputs() throws QueueException, TimeoutException, InterruptedException {
@@ -195,24 +191,24 @@ public class MultipleConditionTriggerCaseTest {
// flowB // flowB
Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions", Execution execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions",
"flow-trigger-preconditions-flow-b", Duration.ofSeconds(60)); "flow-trigger-preconditions-flow-b", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// flowA // flowA
execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions", execution = runnerUtils.runOne(null, "io.kestra.tests.trigger.preconditions",
"flow-trigger-preconditions-flow-a", Duration.ofSeconds(60)); "flow-trigger-preconditions-flow-a", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList().size(), is(1)); assertThat(execution.getTaskRunList().size()).isEqualTo(1);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// trigger is done // trigger is done
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)); assertTrue(countDownLatch.await(1, TimeUnit.SECONDS));
receive.blockLast(); receive.blockLast();
assertThat(flowTrigger.get(), notNullValue()); assertThat(flowTrigger.get()).isNotNull();
Execution triggerExecution = flowTrigger.get(); Execution triggerExecution = flowTrigger.get();
assertThat(triggerExecution.getTaskRunList().size(), is(1)); assertThat(triggerExecution.getTaskRunList().size()).isEqualTo(1);
assertThat(triggerExecution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(triggerExecution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(triggerExecution.getTrigger().getVariables().get("outputs"), notNullValue()); assertThat(triggerExecution.getTrigger().getVariables().get("outputs")).isNotNull();
assertThat((Map<String, Object>) triggerExecution.getTrigger().getVariables().get("outputs"), hasEntry("some", "value")); assertThat((Map<String, Object>) triggerExecution.getTrigger().getVariables().get("outputs")).containsEntry("some", "value");
} }
} }

View File

@@ -19,9 +19,7 @@ import org.junit.jupiter.api.TestInstance;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
@@ -45,23 +43,23 @@ public class NoEncryptionConfiguredTest implements TestPropertyProvider {
@Test @Test
@ExecuteFlow("flows/valids/encrypted-string.yaml") @ExecuteFlow("flows/valids/encrypted-string.yaml")
void encryptedStringOutput(Execution execution) { void encryptedStringOutput(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
TaskRun hello = execution.findTaskRunsByTaskId("hello").getFirst(); TaskRun hello = execution.findTaskRunsByTaskId("hello").getFirst();
Map<String, String> valueOutput = (Map<String, String>) hello.getOutputs().get("value"); Map<String, String> valueOutput = (Map<String, String>) hello.getOutputs().get("value");
assertThat(valueOutput.size(), is(2)); assertThat(valueOutput.size()).isEqualTo(2);
assertThat(valueOutput.get("type"), is(EncryptedString.TYPE)); assertThat(valueOutput.get("type")).isEqualTo(EncryptedString.TYPE);
// the value is not encrypted as there is no encryption key // the value is not encrypted as there is no encryption key
assertThat(valueOutput.get("value"), is("Hello World")); assertThat(valueOutput.get("value")).isEqualTo("Hello World");
TaskRun returnTask = execution.findTaskRunsByTaskId("return").getFirst(); TaskRun returnTask = execution.findTaskRunsByTaskId("return").getFirst();
// the output is automatically decrypted so the return has the decrypted value of the hello task output // the output is automatically decrypted so the return has the decrypted value of the hello task output
assertThat(returnTask.getOutputs().get("value"), is("Hello World")); assertThat(returnTask.getOutputs().get("value")).isEqualTo("Hello World");
} }
@Test @Test
@LoadFlows({"flows/valids/inputs.yaml"}) @LoadFlows({"flows/valids/inputs.yaml"})
void secretInput() { void secretInput() {
assertThat(flowRepository.findById(null, "io.kestra.tests", "inputs").isPresent(), is(true)); assertThat(flowRepository.findById(null, "io.kestra.tests", "inputs").isPresent()).isEqualTo(true);
Flow flow = flowRepository.findById(null, "io.kestra.tests", "inputs").get(); Flow flow = flowRepository.findById(null, "io.kestra.tests", "inputs").get();
Execution execution = Execution.builder() Execution execution = Execution.builder()

View File

@@ -13,8 +13,7 @@ import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
public class NullOutputTest { public class NullOutputTest {
@@ -36,10 +35,10 @@ public class NullOutputTest {
void shouldIncludeNullOutput() throws QueueException, TimeoutException { void shouldIncludeNullOutput() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "null-output"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "null-output");
assertThat(execution, notNullValue()); assertThat(execution).isNotNull();
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getTaskRunList().getFirst().getOutputs(), aMapWithSize(1)); assertThat(execution.getTaskRunList().getFirst().getOutputs()).hasSize(1);
assertThat(execution.getTaskRunList().getFirst().getOutputs().containsKey("value"), is(true)); assertThat(execution.getTaskRunList().getFirst().getOutputs().containsKey("value")).isEqualTo(true);
} }
} }

View File

@@ -24,9 +24,7 @@ import java.util.List;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@Singleton @Singleton
public class PluginDefaultsCaseTest { public class PluginDefaultsCaseTest {
@@ -36,21 +34,21 @@ public class PluginDefaultsCaseTest {
public void taskDefaults() throws TimeoutException, QueueException { public void taskDefaults() throws TimeoutException, QueueException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "plugin-defaults", Duration.ofSeconds(60)); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "plugin-defaults", Duration.ofSeconds(60));
assertThat(execution.getTaskRunList(), hasSize(8)); assertThat(execution.getTaskRunList()).hasSize(8);
assertThat(execution.getTaskRunList().getFirst().getTaskId(), is("first")); assertThat(execution.getTaskRunList().getFirst().getTaskId()).isEqualTo("first");
assertThat(execution.getTaskRunList().getFirst().getOutputs().get("def"), is("1")); assertThat(execution.getTaskRunList().getFirst().getOutputs().get("def")).isEqualTo("1");
assertThat(execution.getTaskRunList().get(1).getTaskId(), is("second")); assertThat(execution.getTaskRunList().get(1).getTaskId()).isEqualTo("second");
assertThat(execution.getTaskRunList().get(1).getOutputs().get("def"), is("2")); assertThat(execution.getTaskRunList().get(1).getOutputs().get("def")).isEqualTo("2");
assertThat(execution.getTaskRunList().get(2).getTaskId(), is("third")); assertThat(execution.getTaskRunList().get(2).getTaskId()).isEqualTo("third");
assertThat(execution.getTaskRunList().get(2).getOutputs().get("def"), is("3")); assertThat(execution.getTaskRunList().get(2).getOutputs().get("def")).isEqualTo("3");
assertThat(execution.getTaskRunList().get(4).getTaskId(), is("err-first")); assertThat(execution.getTaskRunList().get(4).getTaskId()).isEqualTo("err-first");
assertThat(execution.getTaskRunList().get(4).getOutputs().get("def"), is("1")); assertThat(execution.getTaskRunList().get(4).getOutputs().get("def")).isEqualTo("1");
assertThat(execution.getTaskRunList().get(5).getTaskId(), is("err-second")); assertThat(execution.getTaskRunList().get(5).getTaskId()).isEqualTo("err-second");
assertThat(execution.getTaskRunList().get(5).getOutputs().get("def"), is("2")); assertThat(execution.getTaskRunList().get(5).getOutputs().get("def")).isEqualTo("2");
assertThat(execution.getTaskRunList().get(6).getTaskId(), is("err-third")); assertThat(execution.getTaskRunList().get(6).getTaskId()).isEqualTo("err-third");
assertThat(execution.getTaskRunList().get(6).getOutputs().get("def"), is("3")); assertThat(execution.getTaskRunList().get(6).getOutputs().get("def")).isEqualTo("3");
} }
@SuperBuilder @SuperBuilder

View File

@@ -23,9 +23,7 @@ import jakarta.inject.Inject;
import jakarta.inject.Named; import jakarta.inject.Named;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static io.kestra.core.utils.Rethrow.throwRunnable; import static io.kestra.core.utils.Rethrow.throwRunnable;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -49,38 +47,38 @@ public class RestartCaseTest {
Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60)); Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60));
assertThat(firstExecution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(firstExecution.getTaskRunList(), hasSize(3)); assertThat(firstExecution.getTaskRunList()).hasSize(3);
assertThat(firstExecution.getTaskRunList().get(2).getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getTaskRunList().get(2).getState().getCurrent()).isEqualTo(State.Type.FAILED);
// wait // wait
Execution finishedRestartedExecution = runnerUtils.awaitExecution( Execution finishedRestartedExecution = runnerUtils.awaitExecution(
execution -> execution.getState().getCurrent() == State.Type.SUCCESS && execution.getId().equals(firstExecution.getId()), execution -> execution.getState().getCurrent() == State.Type.SUCCESS && execution.getId().equals(firstExecution.getId()),
throwRunnable(() -> { throwRunnable(() -> {
Execution restartedExec = executionService.restart(firstExecution, null); Execution restartedExec = executionService.restart(firstExecution, null);
assertThat(restartedExec, notNullValue()); assertThat(restartedExec).isNotNull();
assertThat(restartedExec.getId(), is(firstExecution.getId())); assertThat(restartedExec.getId()).isEqualTo(firstExecution.getId());
assertThat(restartedExec.getParentId(), nullValue()); assertThat(restartedExec.getParentId()).isNull();
assertThat(restartedExec.getTaskRunList().size(), is(3)); assertThat(restartedExec.getTaskRunList().size()).isEqualTo(3);
assertThat(restartedExec.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restartedExec.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
executionQueue.emit(restartedExec); executionQueue.emit(restartedExec);
}), }),
Duration.ofSeconds(60) Duration.ofSeconds(60)
); );
assertThat(finishedRestartedExecution, notNullValue()); assertThat(finishedRestartedExecution).isNotNull();
assertThat(finishedRestartedExecution.getId(), is(firstExecution.getId())); assertThat(finishedRestartedExecution.getId()).isEqualTo(firstExecution.getId());
assertThat(finishedRestartedExecution.getParentId(), nullValue()); assertThat(finishedRestartedExecution.getParentId()).isNull();
assertThat(finishedRestartedExecution.getTaskRunList().size(), is(4)); assertThat(finishedRestartedExecution.getTaskRunList().size()).isEqualTo(4);
assertThat(finishedRestartedExecution.getTaskRunList().get(2).getAttempts().size(), is(2)); assertThat(finishedRestartedExecution.getTaskRunList().get(2).getAttempts().size()).isEqualTo(2);
finishedRestartedExecution finishedRestartedExecution
.getTaskRunList() .getTaskRunList()
.stream() .stream()
.map(TaskRun::getState) .map(TaskRun::getState)
.forEach(state -> assertThat(state.getCurrent(), is(State.Type.SUCCESS))); .forEach(state -> assertThat(state.getCurrent()).isEqualTo(State.Type.SUCCESS));
} }
public void restartFailedThenFailureWithGlobalErrors() throws Exception { public void restartFailedThenFailureWithGlobalErrors() throws Exception {
@@ -88,9 +86,9 @@ public class RestartCaseTest {
Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60)); Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60));
assertThat(firstExecution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(firstExecution.getTaskRunList(), hasSize(2)); assertThat(firstExecution.getTaskRunList()).hasSize(2);
assertThat(firstExecution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
// wait // wait
Execution finishedRestartedExecution = runnerUtils.awaitExecution( Execution finishedRestartedExecution = runnerUtils.awaitExecution(
@@ -99,23 +97,23 @@ public class RestartCaseTest {
Execution restartedExec = executionService.restart(firstExecution, null); Execution restartedExec = executionService.restart(firstExecution, null);
executionQueue.emit(restartedExec); executionQueue.emit(restartedExec);
assertThat(restartedExec, notNullValue()); assertThat(restartedExec).isNotNull();
assertThat(restartedExec.getId(), is(firstExecution.getId())); assertThat(restartedExec.getId()).isEqualTo(firstExecution.getId());
assertThat(restartedExec.getParentId(), nullValue()); assertThat(restartedExec.getParentId()).isNull();
assertThat(restartedExec.getTaskRunList().size(), is(1)); assertThat(restartedExec.getTaskRunList().size()).isEqualTo(1);
assertThat(restartedExec.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restartedExec.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
}), }),
Duration.ofSeconds(60) Duration.ofSeconds(60)
); );
assertThat(finishedRestartedExecution, notNullValue()); assertThat(finishedRestartedExecution).isNotNull();
assertThat(finishedRestartedExecution.getId(), is(firstExecution.getId())); assertThat(finishedRestartedExecution.getId()).isEqualTo(firstExecution.getId());
assertThat(finishedRestartedExecution.getParentId(), nullValue()); assertThat(finishedRestartedExecution.getParentId()).isNull();
assertThat(finishedRestartedExecution.getTaskRunList().size(), is(2)); assertThat(finishedRestartedExecution.getTaskRunList().size()).isEqualTo(2);
assertThat(finishedRestartedExecution.getTaskRunList().getFirst().getAttempts().size(), is(2)); assertThat(finishedRestartedExecution.getTaskRunList().getFirst().getAttempts().size()).isEqualTo(2);
assertThat(finishedRestartedExecution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(finishedRestartedExecution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
public void restartFailedThenFailureWithLocalErrors() throws Exception { public void restartFailedThenFailureWithLocalErrors() throws Exception {
@@ -123,9 +121,9 @@ public class RestartCaseTest {
Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60)); Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60));
assertThat(firstExecution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(firstExecution.getTaskRunList(), hasSize(5)); assertThat(firstExecution.getTaskRunList()).hasSize(5);
assertThat(firstExecution.getTaskRunList().get(3).getState().getCurrent(), is(State.Type.FAILED)); assertThat(firstExecution.getTaskRunList().get(3).getState().getCurrent()).isEqualTo(State.Type.FAILED);
// wait // wait
Execution finishedRestartedExecution = runnerUtils.awaitExecution( Execution finishedRestartedExecution = runnerUtils.awaitExecution(
@@ -134,25 +132,25 @@ public class RestartCaseTest {
Execution restartedExec = executionService.restart(firstExecution, null); Execution restartedExec = executionService.restart(firstExecution, null);
executionQueue.emit(restartedExec); executionQueue.emit(restartedExec);
assertThat(restartedExec, notNullValue()); assertThat(restartedExec).isNotNull();
assertThat(restartedExec.getId(), is(firstExecution.getId())); assertThat(restartedExec.getId()).isEqualTo(firstExecution.getId());
assertThat(restartedExec.getParentId(), nullValue()); assertThat(restartedExec.getParentId()).isNull();
assertThat(restartedExec.getTaskRunList().size(), is(4)); assertThat(restartedExec.getTaskRunList().size()).isEqualTo(4);
assertThat(restartedExec.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restartedExec.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
}), }),
Duration.ofSeconds(60) Duration.ofSeconds(60)
); );
assertThat(finishedRestartedExecution, notNullValue()); assertThat(finishedRestartedExecution).isNotNull();
assertThat(finishedRestartedExecution.getId(), is(firstExecution.getId())); assertThat(finishedRestartedExecution.getId()).isEqualTo(firstExecution.getId());
assertThat(finishedRestartedExecution.getParentId(), nullValue()); assertThat(finishedRestartedExecution.getParentId()).isNull();
assertThat(finishedRestartedExecution.getTaskRunList().size(), is(5)); assertThat(finishedRestartedExecution.getTaskRunList().size()).isEqualTo(5);
Optional<TaskRun> taskRun = finishedRestartedExecution.findTaskRunsByTaskId("failStep").stream().findFirst(); Optional<TaskRun> taskRun = finishedRestartedExecution.findTaskRunsByTaskId("failStep").stream().findFirst();
assertTrue(taskRun.isPresent()); assertTrue(taskRun.isPresent());
assertThat(taskRun.get().getAttempts().size(), is(2)); assertThat(taskRun.get().getAttempts().size()).isEqualTo(2);
assertThat(finishedRestartedExecution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(finishedRestartedExecution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
public void replay() throws Exception { public void replay() throws Exception {
@@ -160,7 +158,7 @@ public class RestartCaseTest {
Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60)); Execution firstExecution = runnerUtils.runOne(null, flow.getNamespace(), flow.getId(), Duration.ofSeconds(60));
assertThat(firstExecution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(firstExecution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
// wait // wait
Execution finishedRestartedExecution = runnerUtils.awaitChildExecution( Execution finishedRestartedExecution = runnerUtils.awaitChildExecution(
@@ -170,30 +168,30 @@ public class RestartCaseTest {
Execution restartedExec = executionService.replay(firstExecution, firstExecution.findTaskRunByTaskIdAndValue("2_end", List.of()).getId(), null); Execution restartedExec = executionService.replay(firstExecution, firstExecution.findTaskRunByTaskIdAndValue("2_end", List.of()).getId(), null);
executionQueue.emit(restartedExec); executionQueue.emit(restartedExec);
assertThat(restartedExec.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restartedExec.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restartedExec.getState().getHistories(), hasSize(4)); assertThat(restartedExec.getState().getHistories()).hasSize(4);
assertThat(restartedExec.getTaskRunList(), hasSize(20)); assertThat(restartedExec.getTaskRunList()).hasSize(20);
assertThat(restartedExec.getTaskRunList().get(19).getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restartedExec.getTaskRunList().get(19).getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
assertThat(restartedExec.getId(), not(firstExecution.getId())); assertThat(restartedExec.getId()).isNotEqualTo(firstExecution.getId());
assertThat(restartedExec.getTaskRunList().get(1).getId(), not(firstExecution.getTaskRunList().get(1).getId())); assertThat(restartedExec.getTaskRunList().get(1).getId()).isNotEqualTo(firstExecution.getTaskRunList().get(1).getId());
}), }),
Duration.ofSeconds(60) Duration.ofSeconds(60)
); );
assertThat(finishedRestartedExecution, notNullValue()); assertThat(finishedRestartedExecution).isNotNull();
assertThat(finishedRestartedExecution.getId(), is(not(firstExecution.getId()))); assertThat(finishedRestartedExecution.getId()).isNotEqualTo(firstExecution.getId());
assertThat(finishedRestartedExecution.getParentId(), is(firstExecution.getId())); assertThat(finishedRestartedExecution.getParentId()).isEqualTo(firstExecution.getId());
assertThat(finishedRestartedExecution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(finishedRestartedExecution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
public void restartMultiple() throws Exception { public void restartMultiple() throws Exception {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "failed-first"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "failed-first");
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution restart = executionService.restart(execution, null); Execution restart = executionService.restart(execution, null);
assertThat(restart.getState().getCurrent(), is(State.Type.RESTARTED)); assertThat(restart.getState().getCurrent()).isEqualTo(State.Type.RESTARTED);
Execution restartEnded = runnerUtils.awaitExecution( Execution restartEnded = runnerUtils.awaitExecution(
e -> e.getState().getCurrent() == State.Type.FAILED, e -> e.getState().getCurrent() == State.Type.FAILED,
@@ -201,7 +199,7 @@ public class RestartCaseTest {
Duration.ofSeconds(120) Duration.ofSeconds(120)
); );
assertThat(restartEnded.getState().getCurrent(), is(State.Type.FAILED)); assertThat(restartEnded.getState().getCurrent()).isEqualTo(State.Type.FAILED);
Execution newRestart = executionService.restart(restartEnded, null); Execution newRestart = executionService.restart(restartEnded, null);
@@ -211,7 +209,7 @@ public class RestartCaseTest {
Duration.ofSeconds(120) Duration.ofSeconds(120)
); );
assertThat(restartEnded.getState().getCurrent(), is(State.Type.FAILED)); assertThat(restartEnded.getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
public void restartSubflow() throws Exception { public void restartSubflow() throws Exception {
@@ -224,8 +222,8 @@ public class RestartCaseTest {
}); });
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-parent"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "restart-parent");
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
// here we must have 1 failed subflows // here we must have 1 failed subflows
assertTrue(countDownLatch.await(1, TimeUnit.MINUTES)); assertTrue(countDownLatch.await(1, TimeUnit.MINUTES));
@@ -257,7 +255,7 @@ public class RestartCaseTest {
throwRunnable(() -> executionQueue.emit(restarted3)), throwRunnable(() -> executionQueue.emit(restarted3)),
Duration.ofSeconds(10) Duration.ofSeconds(10)
); );
assertThat(execution.getTaskRunList(), hasSize(6)); assertThat(execution.getTaskRunList()).hasSize(6);
assertTrue(successLatch.await(1, TimeUnit.MINUTES)); assertTrue(successLatch.await(1, TimeUnit.MINUTES));
receiveSubflows.blockLast(); receiveSubflows.blockLast();
} }

View File

@@ -19,8 +19,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
class RunContextLoggerTest { class RunContextLoggerTest {
@@ -57,11 +56,11 @@ class RunContextLoggerTest {
matchingLog = TestsUtils.awaitLogs(logs, 5); matchingLog = TestsUtils.awaitLogs(logs, 5);
receive.blockLast(); receive.blockLast();
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.TRACE)).findFirst().orElseThrow().getMessage(), is("trace")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.TRACE)).findFirst().orElseThrow().getMessage()).isEqualTo("trace");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.DEBUG)).findFirst().orElseThrow().getMessage(), is("debug")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.DEBUG)).findFirst().orElseThrow().getMessage()).isEqualTo("debug");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElseThrow().getMessage(), is("info")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElseThrow().getMessage()).isEqualTo("info");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.WARN)).findFirst().orElseThrow().getMessage(), is("warn")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.WARN)).findFirst().orElseThrow().getMessage()).isEqualTo("warn");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.ERROR)).findFirst().orElseThrow().getMessage(), is("error")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.ERROR)).findFirst().orElseThrow().getMessage()).isEqualTo("error");
} }
@Test @Test
@@ -85,7 +84,7 @@ class RunContextLoggerTest {
matchingLog = TestsUtils.awaitLogs(logs, 1); matchingLog = TestsUtils.awaitLogs(logs, 1);
receive.blockLast(); receive.blockLast();
assertThat(matchingLog.stream().findFirst().orElseThrow().getMessage(), is(emptyString())); assertThat(matchingLog.stream().findFirst().orElseThrow().getMessage()).isEmpty();
} }
@Test @Test
@@ -117,9 +116,9 @@ class RunContextLoggerTest {
matchingLog = TestsUtils.awaitLogs(logs, 3); matchingLog = TestsUtils.awaitLogs(logs, 3);
receive.blockLast(); receive.blockLast();
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.DEBUG)).findFirst().orElseThrow().getMessage(), is("test john@******* test")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.DEBUG)).findFirst().orElseThrow().getMessage()).isEqualTo("test john@******* test");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.TRACE)).findFirst().orElseThrow().getMessage(), containsString("exception from doe.com")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.TRACE)).findFirst().orElseThrow().getMessage()).contains("exception from doe.com");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElseThrow().getMessage(), is("test **masked****************** ************* **************************")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElseThrow().getMessage()).isEqualTo("test **masked****************** ************* **************************");
assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.WARN)).findFirst().orElseThrow().getMessage(), is("test **masked**********")); assertThat(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.WARN)).findFirst().orElseThrow().getMessage()).isEqualTo("test **masked**********");
} }
} }

View File

@@ -10,8 +10,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@KestraTest @KestraTest
class RunContextPropertyTest { class RunContextPropertyTest {
@@ -23,10 +22,10 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(); var runContext = runContextFactory.of();
var runContextProperty = new RunContextProperty<String>(null, runContext); var runContextProperty = new RunContextProperty<String>(null, runContext);
assertThat(runContextProperty.as(String.class), is(Optional.empty())); assertThat(runContextProperty.as(String.class)).isEqualTo(Optional.empty());
runContextProperty = new RunContextProperty<>(null, runContext); runContextProperty = new RunContextProperty<>(null, runContext);
assertThat(runContextProperty.as(String.class, Map.of("key", "value")), is(Optional.empty())); assertThat(runContextProperty.as(String.class, Map.of("key", "value"))).isEqualTo(Optional.empty());
} }
@Test @Test
@@ -34,10 +33,10 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(Map.of("variable", "value")); var runContext = runContextFactory.of(Map.of("variable", "value"));
var runContextProperty = new RunContextProperty<>(Property.<String>builder().expression("{{ variable }}").build(), runContext); var runContextProperty = new RunContextProperty<>(Property.<String>builder().expression("{{ variable }}").build(), runContext);
assertThat(runContextProperty.as(String.class).orElseThrow(), is("value")); assertThat(runContextProperty.as(String.class).orElseThrow()).isEqualTo("value");
runContextProperty = new RunContextProperty<>(Property.<String>builder().expression("{{ key }}").build(), runContext); runContextProperty = new RunContextProperty<>(Property.<String>builder().expression("{{ key }}").build(), runContext);
assertThat(runContextProperty.as(String.class, Map.of("key", "value")).orElseThrow(), is("value")); assertThat(runContextProperty.as(String.class, Map.of("key", "value")).orElseThrow()).isEqualTo("value");
} }
@Test @Test
@@ -45,10 +44,10 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(); var runContext = runContextFactory.of();
var runContextProperty = new RunContextProperty<List<String>>(null, runContext); var runContextProperty = new RunContextProperty<List<String>>(null, runContext);
assertThat(runContextProperty.asList(String.class), hasSize(0)); assertThat(runContextProperty.asList(String.class)).hasSize(0);
runContextProperty = new RunContextProperty<>(null, runContext); runContextProperty = new RunContextProperty<>(null, runContext);
assertThat(runContextProperty.asList(String.class, Map.of("key", "value")), hasSize(0)); assertThat(runContextProperty.asList(String.class, Map.of("key", "value"))).hasSize(0);
} }
@Test @Test
@@ -56,10 +55,10 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(Map.of("variable", "value")); var runContext = runContextFactory.of(Map.of("variable", "value"));
var runContextProperty = new RunContextProperty<>(Property.<List<String>>builder().expression("[\"{{ variable }}\"]").build(), runContext); var runContextProperty = new RunContextProperty<>(Property.<List<String>>builder().expression("[\"{{ variable }}\"]").build(), runContext);
assertThat(runContextProperty.asList(String.class), hasItem("value")); assertThat(runContextProperty.asList(String.class)).contains("value");
runContextProperty = new RunContextProperty<>(Property.<List<String>>builder().expression("[\"{{ key }}\"]").build(), runContext); runContextProperty = new RunContextProperty<>(Property.<List<String>>builder().expression("[\"{{ key }}\"]").build(), runContext);
assertThat(runContextProperty.asList(String.class, Map.of("key", "value")), hasItem("value")); assertThat(runContextProperty.asList(String.class, Map.of("key", "value"))).contains("value");
} }
@Test @Test
@@ -67,10 +66,10 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(); var runContext = runContextFactory.of();
var runContextProperty = new RunContextProperty<Map<String, String>>(null, runContext); var runContextProperty = new RunContextProperty<Map<String, String>>(null, runContext);
assertThat(runContextProperty.asMap(String.class, String.class), aMapWithSize(0)); assertThat(runContextProperty.asMap(String.class, String.class)).hasSize(0);
runContextProperty = new RunContextProperty<>(null, runContext); runContextProperty = new RunContextProperty<>(null, runContext);
assertThat(runContextProperty.asMap(String.class, String.class, Map.of("key", "value")), aMapWithSize(0)); assertThat(runContextProperty.asMap(String.class, String.class, Map.of("key", "value"))).hasSize(0);
} }
@Test @Test
@@ -78,9 +77,9 @@ class RunContextPropertyTest {
var runContext = runContextFactory.of(Map.of("variable", "value")); var runContext = runContextFactory.of(Map.of("variable", "value"));
var runContextProperty = new RunContextProperty<>(Property.<Map<String, String>>builder().expression("{ \"key\": \"{{ variable }}\"}").build(), runContext); var runContextProperty = new RunContextProperty<>(Property.<Map<String, String>>builder().expression("{ \"key\": \"{{ variable }}\"}").build(), runContext);
assertThat(runContextProperty.asMap(String.class, String.class), hasEntry("key", "value")); assertThat(runContextProperty.asMap(String.class, String.class)).containsEntry("key", "value");
runContextProperty = new RunContextProperty<>(Property.<Map<String, String>>builder().expression("{ \"key\": \"{{ key }}\"}").build(), runContext); runContextProperty = new RunContextProperty<>(Property.<Map<String, String>>builder().expression("{ \"key\": \"{{ key }}\"}").build(), runContext);
assertThat(runContextProperty.asMap(String.class, String.class, Map.of("key", "value")), hasEntry("key", "value")); assertThat(runContextProperty.asMap(String.class, String.class, Map.of("key", "value"))).containsEntry("key", "value");
} }
} }

View File

@@ -42,7 +42,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.ToString; import lombok.ToString;
import lombok.experimental.SuperBuilder; import lombok.experimental.SuperBuilder;
import org.exparity.hamcrest.date.ZonedDateTimeMatchers;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.event.Level; import org.slf4j.event.Level;
@@ -61,8 +60,9 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
@@ -112,26 +112,26 @@ class RunContextTest {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "logs");
assertThat(execution.getTaskRunList(), hasSize(5)); assertThat(execution.getTaskRunList()).hasSize(5);
matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().getFirst().getId())); matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().getFirst().getId()));
assertThat(matchingLog, notNullValue()); assertThat(matchingLog).isNotNull();
assertThat(matchingLog.getLevel(), is(Level.TRACE)); assertThat(matchingLog.getLevel()).isEqualTo(Level.TRACE);
assertThat(matchingLog.getMessage(), is("first t1")); assertThat(matchingLog.getMessage()).isEqualTo("first t1");
matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(1).getId())); matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(1).getId()));
assertThat(matchingLog, notNullValue()); assertThat(matchingLog).isNotNull();
assertThat(matchingLog.getLevel(), is(Level.WARN)); assertThat(matchingLog.getLevel()).isEqualTo(Level.WARN);
assertThat(matchingLog.getMessage(), is("second io.kestra.plugin.core.log.Log")); assertThat(matchingLog.getMessage()).isEqualTo("second io.kestra.plugin.core.log.Log");
matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(2).getId())); matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(2).getId()));
assertThat(matchingLog, notNullValue()); assertThat(matchingLog).isNotNull();
assertThat(matchingLog.getLevel(), is(Level.ERROR)); assertThat(matchingLog.getLevel()).isEqualTo(Level.ERROR);
assertThat(matchingLog.getMessage(), is("third logs")); assertThat(matchingLog.getMessage()).isEqualTo("third logs");
matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(3).getId())); matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(3).getId()));
receive.blockLast(); receive.blockLast();
assertThat(matchingLog, nullValue()); assertThat(matchingLog).isNull();
} }
@Test @Test
@@ -154,28 +154,27 @@ class RunContextTest {
(flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs) (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs)
); );
assertThat(execution.getTaskRunList(), hasSize(10)); assertThat(execution.getTaskRunList()).hasSize(10);
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList().getFirst().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getTaskRunList().getFirst().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
List<LogEntry> logEntries = TestsUtils.awaitLogs(logs, logEntry -> logEntry.getTaskRunId() != null && logEntry.getTaskRunId().equals(execution.getTaskRunList().get(1).getId()), count -> count > 3); List<LogEntry> logEntries = TestsUtils.awaitLogs(logs, logEntry -> logEntry.getTaskRunId() != null && logEntry.getTaskRunId().equals(execution.getTaskRunList().get(1).getId()), count -> count > 3);
receive.blockLast(); receive.blockLast();
logEntries.sort(Comparator.comparingLong(value -> value.getTimestamp().toEpochMilli())); logEntries.sort(Comparator.comparingLong(value -> value.getTimestamp().toEpochMilli()));
assertThat(logEntries.getFirst().getTimestamp().toEpochMilli(), is(logEntries.get(1).getTimestamp().toEpochMilli())); assertThat(logEntries.getFirst().getTimestamp().toEpochMilli()).isEqualTo(logEntries.get(1).getTimestamp().toEpochMilli());
} }
@Test @Test
@ExecuteFlow("flows/valids/return.yaml") @ExecuteFlow("flows/valids/return.yaml")
void variables(Execution execution) { void variables(Execution execution) {
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat( assertThat(ZonedDateTime.parse((String) execution.getTaskRunList().getFirst().getOutputs().get("value")))
ZonedDateTime.from(ZonedDateTime.parse((String) execution.getTaskRunList().getFirst().getOutputs().get("value"))), .isCloseTo(ZonedDateTime.now(), within(10, ChronoUnit.SECONDS));
ZonedDateTimeMatchers.within(10, ChronoUnit.SECONDS, ZonedDateTime.now())
); assertThat(execution.getTaskRunList().get(1).getOutputs().get("value")).isEqualTo("task-id");
assertThat(execution.getTaskRunList().get(1).getOutputs().get("value"), is("task-id")); assertThat(execution.getTaskRunList().get(2).getOutputs().get("value")).isEqualTo("return");
assertThat(execution.getTaskRunList().get(2).getOutputs().get("value"), is("return"));
} }
@Test @Test
@@ -196,7 +195,7 @@ class RunContextTest {
p.destroy(); p.destroy();
URI uri = runContext.storage().putFile(path.toFile()); URI uri = runContext.storage().putFile(path.toFile());
assertThat(storageInterface.getAttributes(null, null, uri).getSize(), is(size + 1)); assertThat(storageInterface.getAttributes(null, null, uri).getSize()).isEqualTo(size + 1);
} }
@Test @Test
@@ -214,16 +213,16 @@ class RunContextTest {
runContext.metric(Counter.of("counter", 123D, "key", "value")); runContext.metric(Counter.of("counter", 123D, "key", "value"));
runContext.metric(Timer.of("duration", Duration.ofSeconds(123), "key", "value")); runContext.metric(Timer.of("duration", Duration.ofSeconds(123), "key", "value"));
assertThat(runContext.metrics().get(runContext.metrics().indexOf(counter)).getValue(), is(42D)); assertThat(runContext.metrics().get(runContext.metrics().indexOf(counter)).getValue()).isEqualTo(42D);
assertThat(metricRegistry.counter("counter").count(), is(42D)); assertThat(metricRegistry.counter("counter").count()).isEqualTo(42D);
assertThat(runContext.metrics().get(runContext.metrics().indexOf(timer)).getValue(), is(Duration.ofSeconds(42))); assertThat(runContext.metrics().get(runContext.metrics().indexOf(timer)).getValue()).isEqualTo(Duration.ofSeconds(42));
assertThat(metricRegistry.timer("duration").totalTime(TimeUnit.SECONDS), is(42D)); assertThat(metricRegistry.timer("duration").totalTime(TimeUnit.SECONDS)).isEqualTo(42D);
assertThat(runContext.metrics().get(2).getValue(), is(123D)); assertThat(runContext.metrics().get(2).getValue()).isEqualTo(123D);
assertThat(runContext.metrics().get(2).getTags().size(), is(1)); assertThat(runContext.metrics().get(2).getTags().size()).isEqualTo(1);
assertThat(runContext.metrics().get(3).getValue(), is(Duration.ofSeconds(123))); assertThat(runContext.metrics().get(3).getValue()).isEqualTo(Duration.ofSeconds(123));
assertThat(runContext.metrics().get(3).getTags().size(), is(1)); assertThat(runContext.metrics().get(3).getTags().size()).isEqualTo(1);
} }
@Test @Test
@@ -235,25 +234,25 @@ class RunContextTest {
String encrypted = runContext.encrypt(plainText); String encrypted = runContext.encrypt(plainText);
String decrypted = EncryptionService.decrypt(secretKey, encrypted); String decrypted = EncryptionService.decrypt(secretKey, encrypted);
assertThat(encrypted, not(plainText)); assertThat(encrypted).isNotEqualTo(plainText);
assertThat(decrypted, is(plainText)); assertThat(decrypted).isEqualTo(plainText);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
@ExecuteFlow("flows/valids/encrypted-string.yaml") @ExecuteFlow("flows/valids/encrypted-string.yaml")
void encryptedStringOutput(Execution execution) { void encryptedStringOutput(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
TaskRun hello = execution.findTaskRunsByTaskId("hello").getFirst(); TaskRun hello = execution.findTaskRunsByTaskId("hello").getFirst();
Map<String, String> valueOutput = (Map<String, String>) hello.getOutputs().get("value"); Map<String, String> valueOutput = (Map<String, String>) hello.getOutputs().get("value");
assertThat(valueOutput.size(), is(2)); assertThat(valueOutput.size()).isEqualTo(2);
assertThat(valueOutput.get("type"), is(EncryptedString.TYPE)); assertThat(valueOutput.get("type")).isEqualTo(EncryptedString.TYPE);
// the value is encrypted so it's not the plaintext value of the task property // the value is encrypted so it's not the plaintext value of the task property
assertThat(valueOutput.get("value"), not("Hello World")); assertThat(valueOutput.get("value")).isNotEqualTo("Hello World");
TaskRun returnTask = execution.findTaskRunsByTaskId("return").getFirst(); TaskRun returnTask = execution.findTaskRunsByTaskId("return").getFirst();
// the output is automatically decrypted so the return has the decrypted value of the hello task output // the output is automatically decrypted so the return has the decrypted value of the hello task output
assertThat(returnTask.getOutputs().get("value"), is("Hello World")); assertThat(returnTask.getOutputs().get("value")).isEqualTo("Hello World");
} }
@Test @Test
@@ -263,7 +262,7 @@ class RunContextTest {
RunContext runContext = runContextFactory.of(flow, execution); RunContext runContext = runContextFactory.of(flow, execution);
assertThat(runContext.render("{{inputs.test}}"), is("test")); assertThat(runContext.render("{{inputs.test}}")).isEqualTo("test");
} }
@Test @Test
@@ -273,7 +272,7 @@ class RunContextTest {
RunContext runContext = runContextFactory.of(flow, execution); RunContext runContext = runContextFactory.of(flow, execution);
assertThat(runContext.render("{{inputs.test}}"), is("test")); assertThat(runContext.render("{{inputs.test}}")).isEqualTo("test");
} }
@Test @Test
@@ -284,13 +283,13 @@ class RunContextTest {
)); ));
Map<String, String> rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}")); Map<String, String> rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}"));
assertThat(rendered.get("default"), is("default")); assertThat(rendered.get("default")).isEqualTo("default");
rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}"), Map.of( rendered = runContext.renderMap(Map.of("{{key}}", "{{value}}"), Map.of(
"key", "key", "key", "key",
"value", "value" "value", "value"
)); ));
assertThat(rendered.get("key"), is("value")); assertThat(rendered.get("key")).isEqualTo("value");
} }
@@ -320,7 +319,7 @@ class RunContextTest {
matchingLog = TestsUtils.awaitLogs(logs, 3); matchingLog = TestsUtils.awaitLogs(logs, 3);
receive.blockLast(); receive.blockLast();
assertThat(Objects.requireNonNull(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElse(null)).getMessage(), is("john ******** doe")); assertThat(Objects.requireNonNull(matchingLog.stream().filter(logEntry -> logEntry.getLevel().equals(Level.INFO)).findFirst().orElse(null)).getMessage()).isEqualTo("john ******** doe");
} }
@Test @Test

View File

@@ -9,8 +9,7 @@ import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
class RunVariablesTest { class RunVariablesTest {
@@ -18,10 +17,10 @@ class RunVariablesTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
void shouldGetEmptyVariables() { void shouldGetEmptyVariables() {
Map<String, Object> variables = new RunVariables.DefaultBuilder().build(new RunContextLogger()); Map<String, Object> variables = new RunVariables.DefaultBuilder().build(new RunContextLogger());
assertThat(variables.size(), is(3)); assertThat(variables.size()).isEqualTo(3);
assertThat((Map<String, Object>) variables.get("envs"), is(Map.of())); assertThat((Map<String, Object>) variables.get("envs")).isEqualTo(Map.of());
assertThat((Map<String, Object>) variables.get("globals"), is(Map.of())); assertThat((Map<String, Object>) variables.get("globals")).isEqualTo(Map.of());
assertThat(variables.get("addSecretConsumer"), notNullValue()); assertThat(variables.get("addSecretConsumer")).isNotNull();
} }
@Test @Test
@@ -104,10 +103,10 @@ class RunVariablesTest {
Map<String, Object> variables = new RunVariables.DefaultBuilder() Map<String, Object> variables = new RunVariables.DefaultBuilder()
.withKestraConfiguration(new RunVariables.KestraConfiguration("test", "http://localhost:8080")) .withKestraConfiguration(new RunVariables.KestraConfiguration("test", "http://localhost:8080"))
.build(new RunContextLogger()); .build(new RunContextLogger());
assertThat(variables.size(), is(4)); assertThat(variables.size()).isEqualTo(4);
Map<String, Object> kestra = (Map<String, Object>) variables.get("kestra"); Map<String, Object> kestra = (Map<String, Object>) variables.get("kestra");
assertThat(kestra, aMapWithSize(2)); assertThat(kestra).hasSize(2);
assertThat(kestra.get("environment"), is("test")); assertThat(kestra.get("environment")).isEqualTo("test");
assertThat(kestra.get("url"), is("http://localhost:8080")); assertThat(kestra.get("url")).isEqualTo("http://localhost:8080");
} }
} }

View File

@@ -1,8 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import io.kestra.core.junit.annotations.ExecuteFlow; import io.kestra.core.junit.annotations.ExecuteFlow;
import io.kestra.core.junit.annotations.KestraTest; import io.kestra.core.junit.annotations.KestraTest;
@@ -15,8 +13,8 @@ class RunnableTaskExceptionTest {
@Test @Test
@ExecuteFlow("flows/valids/exception-with-output.yaml") @ExecuteFlow("flows/valids/exception-with-output.yaml")
void simple(Execution execution) { void simple(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getTaskRunList()).hasSize(1);
assertThat(execution.getTaskRunList().get(0).getOutputs().get("message"), is("Oh no!")); assertThat(execution.getTaskRunList().get(0).getOutputs().get("message")).isEqualTo("Oh no!");
} }
} }

View File

@@ -10,9 +10,7 @@ import jakarta.inject.Singleton;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.CoreMatchers.hasItem; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@Singleton @Singleton
public class SLATestCase { public class SLATestCase {
@@ -22,31 +20,31 @@ public class SLATestCase {
public void maxDurationSLAShouldFail() throws QueueException, TimeoutException { public void maxDurationSLAShouldFail() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-max-duration-fail"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-max-duration-fail");
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
public void maxDurationSLAShouldPass() throws QueueException, TimeoutException { public void maxDurationSLAShouldPass() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-max-duration-ok"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-max-duration-ok");
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
public void executionConditionSLAShouldPass() throws QueueException, TimeoutException { public void executionConditionSLAShouldPass() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition");
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
} }
public void executionConditionSLAShouldCancel() throws QueueException, TimeoutException { public void executionConditionSLAShouldCancel() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition", null, (f, e) -> Map.of("string", "CANCEL")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition", null, (f, e) -> Map.of("string", "CANCEL"));
assertThat(execution.getState().getCurrent(), is(State.Type.CANCELLED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.CANCELLED);
} }
public void executionConditionSLAShouldLabel() throws QueueException, TimeoutException { public void executionConditionSLAShouldLabel() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition", null, (f, e) -> Map.of("string", "LABEL")); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "sla-execution-condition", null, (f, e) -> Map.of("string", "LABEL"));
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getLabels(), hasItem(new Label("sla", "violated"))); assertThat(execution.getLabels()).contains(new Label("sla", "violated"));
} }
} }

View File

@@ -18,8 +18,7 @@ import java.util.Optional;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@Singleton @Singleton
@@ -37,8 +36,8 @@ public class ScheduleDateCaseTest {
Execution execution = Execution.newExecution(flow, null, null, Optional.of(scheduleOn)); Execution execution = Execution.newExecution(flow, null, null, Optional.of(scheduleOn));
this.executionQueue.emit(execution); this.executionQueue.emit(execution);
assertThat(execution.getState().getCurrent(), is(State.Type.CREATED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.CREATED);
assertThat(execution.getScheduleDate(), is(scheduleOn.toInstant())); assertThat(execution.getScheduleDate()).isEqualTo(scheduleOn.toInstant());
CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch1 = new CountDownLatch(1);

View File

@@ -22,8 +22,7 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
@Singleton @Singleton
public class SkipExecutionCaseTest { public class SkipExecutionCaseTest {
@@ -50,9 +49,9 @@ public class SkipExecutionCaseTest {
Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "minimal"); Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "minimal");
// the execution 2 should be in success and the 1 still created // the execution 2 should be in success and the 1 still created
assertThat(execution2.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution2.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
execution1 = Await.until(() -> executionRepository.findById(null, execution1Id).orElse(null), Duration.ofMillis(100), Duration.ofSeconds(1)); execution1 = Await.until(() -> executionRepository.findById(null, execution1Id).orElse(null), Duration.ofMillis(100), Duration.ofSeconds(1));
assertThat(execution1.getState().getCurrent(), is(State.Type.CREATED)); assertThat(execution1.getState().getCurrent()).isEqualTo(State.Type.CREATED);
} }
private Flow createFlow() { private Flow createFlow() {

View File

@@ -1,8 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import io.kestra.core.junit.annotations.ExecuteFlow; import io.kestra.core.junit.annotations.ExecuteFlow;
import io.kestra.core.junit.annotations.KestraTest; import io.kestra.core.junit.annotations.KestraTest;
@@ -39,9 +37,9 @@ public class TaskWithAllowFailureTest {
@Test @Test
@ExecuteFlow("flows/valids/task-allow-failure-runnable.yml") @ExecuteFlow("flows/valids/task-allow-failure-runnable.yml")
void runnableTask(Execution execution) { void runnableTask(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.WARNING)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.WARNING);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
assertThat(execution.findTaskRunsByTaskId("fail").getFirst().getAttempts().size(), is(3)); assertThat(execution.findTaskRunsByTaskId("fail").getFirst().getAttempts().size()).isEqualTo(3);
} }
@Test @Test
@@ -49,8 +47,8 @@ public class TaskWithAllowFailureTest {
"flows/valids/for-each-item-subflow-failed.yaml"}) "flows/valids/for-each-item-subflow-failed.yaml"})
void executableTask_Flow() throws QueueException, TimeoutException { void executableTask_Flow() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-failure-executable-flow"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-failure-executable-flow");
assertThat(execution.getState().getCurrent(), is(State.Type.WARNING)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.WARNING);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
} }
@Test @Test
@@ -61,15 +59,15 @@ public class TaskWithAllowFailureTest {
Map<String, Object> inputs = Map.of("file", file.toString()); Map<String, Object> inputs = Map.of("file", file.toString());
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-failure-executable-foreachitem", null, (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs)); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-failure-executable-foreachitem", null, (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs));
assertThat(execution.getState().getCurrent(), is(State.Type.WARNING)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.WARNING);
assertThat(execution.getTaskRunList(), hasSize(4)); assertThat(execution.getTaskRunList()).hasSize(4);
} }
@Test @Test
@ExecuteFlow("flows/valids/task-allow-failure-flowable.yml") @ExecuteFlow("flows/valids/task-allow-failure-flowable.yml")
void flowableTask(Execution execution) { void flowableTask(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.WARNING)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.WARNING);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
} }
private URI storageUpload() throws URISyntaxException, IOException { private URI storageUpload() throws URISyntaxException, IOException {

View File

@@ -22,9 +22,7 @@ import java.util.Map;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
public class TaskWithAllowWarningTest { public class TaskWithAllowWarningTest {
@@ -40,9 +38,9 @@ public class TaskWithAllowWarningTest {
@Test @Test
@ExecuteFlow("flows/valids/task-allow-warning-runnable.yml") @ExecuteFlow("flows/valids/task-allow-warning-runnable.yml")
void runnableTask(Execution execution) { void runnableTask(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
assertThat(execution.findTaskRunsByTaskId("fail").getFirst().getAttempts().size(), is(3)); assertThat(execution.findTaskRunsByTaskId("fail").getFirst().getAttempts().size()).isEqualTo(3);
} }
@Test @Test
@@ -50,8 +48,8 @@ public class TaskWithAllowWarningTest {
"flows/valids/for-each-item-subflow-failed.yaml"}) "flows/valids/for-each-item-subflow-failed.yaml"})
void executableTask_Flow() throws QueueException, TimeoutException { void executableTask_Flow() throws QueueException, TimeoutException {
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-warning-executable-flow"); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-warning-executable-flow");
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList()).hasSize(2);
} }
@Test @Test
@@ -61,15 +59,15 @@ public class TaskWithAllowWarningTest {
Map<String, Object> inputs = Map.of("file", file.toString()); Map<String, Object> inputs = Map.of("file", file.toString());
Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-warning-executable-foreachitem", null, (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs)); Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "task-allow-warning-executable-foreachitem", null, (flow, execution1) -> flowIO.readExecutionInputs(flow, execution1, inputs));
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(4)); assertThat(execution.getTaskRunList()).hasSize(4);
} }
@Test @Test
@ExecuteFlow("flows/valids/task-allow-warning-flowable.yml") @ExecuteFlow("flows/valids/task-allow-warning-flowable.yml")
void flowableTask(Execution execution) { void flowableTask(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
} }
private URI storageUpload() throws URISyntaxException, IOException { private URI storageUpload() throws URISyntaxException, IOException {

View File

@@ -6,9 +6,7 @@ import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.flows.State; import io.kestra.core.models.flows.State;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
@KestraTest(startRunner = true) @KestraTest(startRunner = true)
class TaskWithRunIfTest { class TaskWithRunIfTest {
@@ -16,21 +14,21 @@ class TaskWithRunIfTest {
@Test @Test
@ExecuteFlow("flows/valids/task-runif.yml") @ExecuteFlow("flows/valids/task-runif.yml")
void runnableTask(Execution execution) { void runnableTask(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.FAILED);
assertThat(execution.getTaskRunList(), hasSize(5)); assertThat(execution.getTaskRunList()).hasSize(5);
assertThat(execution.findTaskRunsByTaskId("executed").getFirst().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.findTaskRunsByTaskId("executed").getFirst().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.findTaskRunsByTaskId("notexecuted").getFirst().getState().getCurrent(), is(State.Type.SKIPPED)); assertThat(execution.findTaskRunsByTaskId("notexecuted").getFirst().getState().getCurrent()).isEqualTo(State.Type.SKIPPED);
assertThat(execution.findTaskRunsByTaskId("notexecutedflowable").getFirst().getState().getCurrent(), is(State.Type.SKIPPED)); assertThat(execution.findTaskRunsByTaskId("notexecutedflowable").getFirst().getState().getCurrent()).isEqualTo(State.Type.SKIPPED);
assertThat(execution.findTaskRunsByTaskId("willfailedtheflow").getFirst().getState().getCurrent(), is(State.Type.FAILED)); assertThat(execution.findTaskRunsByTaskId("willfailedtheflow").getFirst().getState().getCurrent()).isEqualTo(State.Type.FAILED);
} }
@Test @Test
@ExecuteFlow("flows/valids/task-runif-workingdirectory.yml") @ExecuteFlow("flows/valids/task-runif-workingdirectory.yml")
void runIfWorkingDirectory(Execution execution) { void runIfWorkingDirectory(Execution execution) {
assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(execution.getTaskRunList()).hasSize(3);
assertThat(execution.findTaskRunsByTaskId("log_orders").getFirst().getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.findTaskRunsByTaskId("log_orders").getFirst().getState().getCurrent()).isEqualTo(State.Type.SUCCESS);
assertThat(execution.findTaskRunsByTaskId("log_test").getFirst().getState().getCurrent(), is(State.Type.SKIPPED)); assertThat(execution.findTaskRunsByTaskId("log_test").getFirst().getState().getCurrent()).isEqualTo(State.Type.SKIPPED);
} }
} }

View File

@@ -1,7 +1,6 @@
package io.kestra.core.runners; package io.kestra.core.runners;
import static org.hamcrest.MatcherAssert.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.contains;
import io.kestra.core.exceptions.IllegalVariableEvaluationException; import io.kestra.core.exceptions.IllegalVariableEvaluationException;
import io.micronaut.context.ApplicationContext; import io.micronaut.context.ApplicationContext;
@@ -46,10 +45,10 @@ class VariableRendererTest {
input.put("foo-3", input_value3); input.put("foo-3", input_value3);
final Map<String, Object> result = variableRenderer.render(input, Map.of()); final Map<String, Object> result = variableRenderer.render(input, Map.of());
assertThat(result.keySet(), contains("foo-1", "foo-2", "foo-3")); assertThat(result.keySet()).containsExactly("foo-1", "foo-2", "foo-3");
final Map<String, Object> result_value3 = (Map<String, Object>) result.get("foo-3"); final Map<String, Object> result_value3 = (Map<String, Object>) result.get("foo-3");
assertThat(result_value3.keySet(), contains("bar-1", "bar-2", "bar-3")); assertThat(result_value3.keySet()).containsExactly("bar-1", "bar-2", "bar-3");
} }
public static class TestVariableRenderer extends VariableRenderer { public static class TestVariableRenderer extends VariableRenderer {

Some files were not shown because too many files have changed in this diff Show More