Skip to content

Commit

Permalink
Add ShellStrategy
Browse files Browse the repository at this point in the history
`ShellStrategy` can also be used as `Wait.forSuccessfulCommand(...)`.

Co-authored-by: Eddú Meléndez <eddu.melendez@gmail.com>
  • Loading branch information
m4rii0 and eddumelendez committed Feb 28, 2023
1 parent 48083c1 commit 8f49046
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
@@ -0,0 +1,32 @@
package org.testcontainers.containers.wait.strategy;

import org.rnorth.ducttape.TimeoutException;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.containers.ContainerLaunchException;

import java.util.concurrent.TimeUnit;

public class ShellStrategy extends AbstractWaitStrategy {

private String command;

public ShellStrategy withCommand(String command) {
this.command = command;
return this;
}

@Override
protected void waitUntilReady() {
try {
Unreliables.retryUntilTrue(
(int) startupTimeout.getSeconds(),
TimeUnit.SECONDS,
() -> waitStrategyTarget.execInContainer("/bin/sh", "-c", this.command).getExitCode() == 0
);
} catch (TimeoutException e) {
throw new ContainerLaunchException(
"Timed out waiting for container to execute `" + this.command + "` successfully."
);
}
}
}
Expand Up @@ -66,4 +66,14 @@ public static LogMessageWaitStrategy forLogMessage(String regex, int times) {
public static DockerHealthcheckWaitStrategy forHealthcheck() {
return new DockerHealthcheckWaitStrategy();
}

/**
* Convenience method to return a WaitStrategy for a shell command.
*
* @param command the command to run
* @return ShellStrategy
*/
public static ShellStrategy forSuccessfulCommand(String command) {
return new ShellStrategy().withCommand(command);
}
}
@@ -0,0 +1,42 @@
package org.testcontainers.junit.wait.strategy;

import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.testcontainers.containers.wait.strategy.ShellStrategy;

import java.util.concurrent.atomic.AtomicBoolean;

/**
* Tests for {@link ShellStrategy}.
*/
public class ShellStrategyTest extends AbstractWaitStrategyTest<ShellStrategy> {

private static final String LOCK_FILE = "/tmp/ready.lock";

@Test
public void testWaitUntilReady_Success() {
waitUntilReadyAndSucceed(String.format("touch %s; sleep 300", LOCK_FILE));
}

@Test
public void testWaitUntilReady_Timeout() {
waitUntilReadyAndTimeout("sleep 300");
}

@NotNull
@Override
protected ShellStrategy buildWaitStrategy(AtomicBoolean ready) {
return createShellStrategy(ready).withCommand(String.format("stat %s", LOCK_FILE));
}

@NotNull
private static ShellStrategy createShellStrategy(AtomicBoolean ready) {
return new ShellStrategy() {
@Override
protected void waitUntilReady() {
super.waitUntilReady();
ready.set(true);
}
};
}
}

0 comments on commit 8f49046

Please sign in to comment.