下面列出了怎么用org.testcontainers.containers.Container.ExecResult的API类实例代码及写法,或者点击链接到github查看源代码。
@AfterEach
public void tearDown() throws IOException, InterruptedException {
SfdxCommand sfdxCommand = SfdxCommand.forceDataRecordDelete()
.withArgument("--sobjecttype", "Account")
.withArgument("--where", String.format("Name=%s", accountName));
LOG.debug("Deleting the test account {}", accountName);
ExecResult result = container.execCommand(sfdxCommand);
if (!verifyCommand(sfdxCommand, result)) {
fail("Unable to delete the test account on Salesforce");
}
accountName = null;
deleteKafkaTopic(TestUtils.getDefaultTestTopic(this.getClass()));
}
@BeforeEach
public void setUp() throws IOException, InterruptedException {
received = false;
account = "TestAccount" + TestUtils.randomWithRange(1, 100);
SfdxCommand sfdxCommand = SfdxCommand.forceDataRecordCreate()
.withArgument("--sobjecttype", "Account")
.withArgument("--values", String.format("Name=%s", account));
LOG.debug("Creating the test account");
ExecResult result = container.execCommand(sfdxCommand);
if (!verifyCommand(sfdxCommand, result)) {
fail("Unable to create test account on Salesforce");
}
}
@Override
public Boolean call() {
String command = "true";
for (int internalPort : internalPorts) {
command += " && ";
command += " (";
command += format("cat /proc/net/tcp* | awk '{print $2}' | grep -i ':0*%x'", internalPort);
command += " || ";
command += format("nc -vz -w 1 localhost %d", internalPort);
command += " || ";
command += format("/bin/bash -c '</dev/tcp/localhost/%d'", internalPort);
command += ")";
}
Instant before = Instant.now();
try {
ExecResult result = ExecInContainerPattern.execInContainer(waitStrategyTarget.getContainerInfo(), "/bin/sh", "-c", command);
log.trace("Check for {} took {}", internalPorts, Duration.between(before, Instant.now()));
return result.getExitCode() == 0;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@AfterEach
public void tearDown() throws IOException, InterruptedException {
SfdxCommand sfdxCommand = SfdxCommand.forceDataRecordDelete()
.withArgument("--sobjecttype", "Account")
.withArgument("--where", String.format("Name=%s", account));
LOG.debug("Deleting the test account");
ExecResult result = container.execCommand(sfdxCommand);
if (!verifyCommand(sfdxCommand, result)) {
fail("Unable to delete the test account on Salesforce");
}
account = null;
deleteKafkaTopic(TestUtils.getDefaultTestTopic(this.getClass()));
}
static void exec(String... command) {
try {
ExecResult execResult = POSTGRESQL_CONTAINER.execInContainer(command);
OkapiLogger.get().debug(() -> String.join(" ", command) + " " + execResult);
} catch (InterruptedException|IOException|UnsupportedOperationException e) {
throw new RuntimeException(e);
}
}
void declareQueue(String queue) {
ExecResult result;
try {
result = container.execInContainer("rabbitmqadmin", "declare", "queue", "name=" + queue);
} catch (Throwable e) {
propagateIfFatal(e);
throw new AssumptionViolatedException(
"Couldn't declare queue " + queue + ": " + e.getMessage(), e);
}
if (result.getExitCode() != 0) {
throw new AssumptionViolatedException("Couldn't declare queue " + queue + ": " + result);
}
}
@Override
public void prepareSource() throws Exception {
ExecResult execResult = kafkaContainer.execInContainer(
"/usr/bin/kafka-topics",
"--create",
"--zookeeper",
"localhost:2181",
"--partitions",
"1",
"--replication-factor",
"1",
"--topic",
kafkaTopicName);
assertTrue(
execResult.getStdout().contains("Created topic"),
execResult.getStdout());
kafkaConsumer = new KafkaConsumer<>(
ImmutableMap.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaContainer.getBootstrapServers(),
ConsumerConfig.GROUP_ID_CONFIG, "source-test-" + randomName(8),
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"
),
new StringDeserializer(),
new StringDeserializer()
);
kafkaConsumer.subscribe(Arrays.asList(kafkaTopicName));
log.info("Successfully subscribe to kafka topic {}", kafkaTopicName);
}
@Override
public void prepareSink() throws Exception {
ExecResult execResult = serviceContainer.execInContainer(
"/usr/bin/kafka-topics",
"--create",
"--zookeeper",
"localhost:2181",
"--partitions",
"1",
"--replication-factor",
"1",
"--topic",
kafkaTopicName);
assertTrue(
execResult.getStdout().contains("Created topic"),
execResult.getStdout());
kafkaConsumer = new KafkaConsumer<>(
ImmutableMap.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, serviceContainer.getBootstrapServers(),
ConsumerConfig.GROUP_ID_CONFIG, "sink-test-" + randomName(8),
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"
),
new StringDeserializer(),
new StringDeserializer()
);
kafkaConsumer.subscribe(Arrays.asList(kafkaTopicName));
log.info("Successfully subscribe to kafka topic {}", kafkaTopicName);
}
@NotNull
private User createUser(@NotNull String username, @NotNull String email, @NotNull String password) throws Exception {
// Need to create user using command line because users now default to requiring to change password
ExecResult createUserHelpResult = gitea.execInContainer("gitea", "admin", "create-user", "--help", "-c", "/data/gitea/conf/app.ini");
boolean mustChangePassword = createUserHelpResult.getStdout().contains("--must-change-password");
String mustChangePasswordString = mustChangePassword ? "--must-change-password=false" : "";
gitea.execInContainer("gitea", "admin", "create-user", "--name", username,
"--password", password, "--email", email,
mustChangePasswordString, "-c", "/data/gitea/conf/app.ini");
ApiClient apiClient = GiteaContext.connect(giteaApiUrl, administratorToken);
UserApi userApi = new UserApi(sudo(apiClient, username));
return userApi.userGetCurrent();
}
@BeforeClass
void before() throws Exception {
SvnTestHelper.skipTestIfDockerUnavailable();
String giteaVersion = System.getenv("GITEA_VERSION");
if (giteaVersion == null) {
SvnTestHelper.skipTestIfRunningOnCI();
giteaVersion = "latest";
}
final int hostPort = 9999;
final int containerPort = 3000;
final String hostname = DockerClientFactory.instance().dockerHostIpAddress();
giteaUrl = String.format("http://%s:%s", hostname, hostPort);
giteaApiUrl = giteaUrl + "/api/v1";
gitea = new FixedHostPortGenericContainer<>("gitea/gitea:" + giteaVersion)
.withFixedExposedPort(hostPort, containerPort)
.withExposedPorts(containerPort)
.withEnv("ROOT_URL", giteaUrl)
.withEnv("INSTALL_LOCK", "true")
.withEnv("SECRET_KEY", "CmjF5WBUNZytE2C80JuogljLs5enS0zSTlikbP2HyG8IUy15UjkLNvTNsyYW7wN")
.withEnv("RUN_MODE", "prod")
.withEnv("LFS_START_SERVER", "true")
.waitingFor(Wait.forHttp("/user/login"))
.withLogConsumer(new Slf4jLogConsumer(log));
gitea.start();
ExecResult createUserHelpResult = gitea.execInContainer("gitea", "admin", "create-user", "--help", "-c", "/data/gitea/conf/app.ini");
boolean mustChangePassword = createUserHelpResult.getStdout().contains("--must-change-password");
String mustChangePasswordString = mustChangePassword ? "--must-change-password=false" : "";
{
ExecResult result = gitea.execInContainer("gitea", "admin", "create-user", "--name", administrator,
"--password", administratorPassword, "--email", "[email protected]", "--admin",
mustChangePasswordString, "-c", "/data/gitea/conf/app.ini");
System.out.println(result.getStdout());
System.err.println(result.getStderr());
}
ApiClient apiClient = new ApiClient();
apiClient.setBasePath(giteaApiUrl);
apiClient.setUsername(administrator);
apiClient.setPassword(administratorPassword);
UserApi userApi = new UserApi(apiClient);
AccessTokenName accessTokenName = new AccessTokenName();
accessTokenName.setName("integration-test");
AccessToken token = userApi.userCreateToken(administrator, accessTokenName);
administratorToken = new GiteaToken(token.getSha1());
// Switch to the GiteaContext approach
// CreateTestUser
final User testUser = createUser(user, userPassword);
Assert.assertNotNull(testUser);
final User collaboratorUser = createUser(collaborator, collaboratorPassword);
Assert.assertNotNull(collaboratorUser);
// Create a repository for the test user
testPublicRepository = createRepository(user, "public-user-repo", "Public User Repository", false, true);
Assert.assertNotNull(testPublicRepository);
testPrivateRepository = createRepository(user, "private-user-repo", "Private User Repository", true, true);
Assert.assertNotNull(testPrivateRepository);
}