Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add environment variables and labels support to @QuarkusIntegrationTest #33840

Merged
merged 3 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ public class TestConfig {
@ConfigItem(defaultValue = "")
Optional<List<String>> argLine;

/**
* Additional environment variables to be set in the process that {@code @QuarkusIntegrationTest} launches.
*/
@ConfigItem
Map<String, String> env;

/**
* Used in {@code @QuarkusIntegrationTest} to determine how long the test will wait for the
* application to launch
Expand Down Expand Up @@ -287,6 +293,12 @@ public static class Container {
*/
@ConfigItem
Map<String, String> additionalExposedPorts;

/**
* A set of labels to add to the launched container
*/
@ConfigItem
Map<String, String> labels;
}

public enum Mode {
Expand Down
3 changes: 3 additions & 0 deletions integration-tests/test-extension/tests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@
<classpathEntriesRecordingFile>${project.build.directory}/recorded-classpath-entries-failsafe.txt</classpathEntriesRecordingFile>
<quarkus.dymmy>test</quarkus.dymmy>
</systemPropertyVariables>
<environmentVariables>
<DUMMY_AGE>70</DUMMY_AGE> <!-- Used to test that env vars are propagated -->
</environmentVariables>
</configuration>
</plugin>
</plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package io.quarkus.it.extension;

import io.quarkus.arc.Unremovable;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;

@ConfigMapping(prefix = "dummy")
@Unremovable
public interface DummyMapping {

@WithDefault("foo")
String name();

@WithDefault("50")
int age();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.quarkus.it.extension;

import java.io.IOException;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import io.quarkus.arc.Arc;

@WebServlet(name = "EnvironmentVariableTestEndpoint", urlPatterns = "/core/env")
public class EnvironmentVariableTestEndpoint extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DummyMapping dummyMapping = Arc.container().select(DummyMapping.class).get();
resp.getWriter().write(dummyMapping.name() + "-" + dummyMapping.age());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,5 @@ quarkus.bt.classpath-recording.resources=io/quarkus/it/extension/ClasspathTestEn
quarkus.bt.classpath-recording.record-file=${project.build.directory}/classpath-entries.txt
%test.quarkus.bt.classpath-recording.record-file=${project.build.directory}/classpath-entries-jvm-tests.txt
quarkus.native.resources.includes=some-resource-for-classpath-test.txt

quarkus.test.env.DUMMY_NAME=bar
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.quarkus.it.extension;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusIntegrationTest;

@QuarkusIntegrationTest
public class EnvVarGraalITCase {

@Test
public void test() {
when().get("/core/env").then()
.body(is("bar-70"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.quarkus.it.extension;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class EnvVarTestCase {

@Test
public void test() {
when().get("/core/env").then()
.body(is("foo-50"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ interface InitContext {

List<String> argLine();

/**
* Additional environment variables to be passed to the launched process.
* Note: When Quarkus launches the new process, it will always include the environment
* variables of the current process
*/
Map<String, String> env();

ArtifactLauncher.InitContext.DevServicesLaunchResult getDevServicesLaunchResult();

interface DevServicesLaunchResult extends AutoCloseable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ public class DefaultDockerContainerLauncher implements DockerContainerArtifactLa
private long waitTimeSeconds;
private String testProfile;
private List<String> argLine;
private Map<String, String> env;
private ArtifactLauncher.InitContext.DevServicesLaunchResult devServicesLaunchResult;
private String containerImage;
private boolean pullRequired;
private Map<Integer, Integer> additionalExposedPorts;

private Map<String, String> labels;
private final Map<String, String> systemProps = new HashMap<>();
private boolean isSsl;
private final String containerName = "quarkus-integration-test-" + RandomStringUtils.random(5, true, false);
Expand All @@ -54,10 +57,12 @@ public void init(DockerContainerArtifactLauncher.DockerInitContext initContext)
this.waitTimeSeconds = initContext.waitTime().getSeconds();
this.testProfile = initContext.testProfile();
this.argLine = initContext.argLine();
this.env = initContext.env();
this.devServicesLaunchResult = initContext.getDevServicesLaunchResult();
this.containerImage = initContext.containerImage();
this.pullRequired = initContext.pullRequired();
this.additionalExposedPorts = initContext.additionalExposedPorts();
this.labels = initContext.labels();
}

@Override
Expand Down Expand Up @@ -127,9 +132,18 @@ public void start() throws IOException {
args.addAll(toEnvVar("quarkus.profile", testProfile));
}

for (Map.Entry<String, String> e : systemProps.entrySet()) {
for (var e : systemProps.entrySet()) {
args.addAll(toEnvVar(e.getKey(), e.getValue()));
}

for (var e : env.entrySet()) {
args.addAll(envAsLaunchArg(e.getKey(), e.getValue()));
}

for (var e : labels.entrySet()) {
args.add("--label");
args.add(e.getKey() + "=" + e.getValue());
}
args.add(containerImage);

final Path logFile = PropertyTestUtil.getLogFilePath();
Expand Down Expand Up @@ -180,9 +194,13 @@ public void includeAsSysProps(Map<String, String> systemProps) {
this.systemProps.putAll(systemProps);
}

private static List<String> envAsLaunchArg(String name, String value) {
return List.of("--env", String.format("%s=%s", name, value));
}

private List<String> toEnvVar(String property, String value) {
if ((property != null) && (!property.isEmpty())) {
return List.of("--env", String.format("%s=%s", convertPropertyToEnvVar(property), value));
return envAsLaunchArg(convertPropertyToEnvVar(property), value);
}
return Collections.emptyList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class DefaultJarLauncher implements JarArtifactLauncher {
private long waitTimeSeconds;
private String testProfile;
private List<String> argLine;
private Map<String, String> env;
private Path jarPath;

private final Map<String, String> systemProps = new HashMap<>();
Expand All @@ -55,6 +56,7 @@ public void init(JarArtifactLauncher.JarInitContext initContext) {
this.waitTimeSeconds = initContext.waitTime().getSeconds();
this.testProfile = initContext.testProfile();
this.argLine = initContext.argLine();
this.env = initContext.env();
this.jarPath = initContext.jarPath();
}

Expand Down Expand Up @@ -127,9 +129,9 @@ public void start(String[] programArgs, boolean handleIo) throws IOException {
Files.createDirectories(logFile.getParent());

if (handleIo) {
quarkusProcess = LauncherUtil.launchProcess(args);
quarkusProcess = LauncherUtil.launchProcessAndDrainIO(args, env);
} else {
quarkusProcess = Runtime.getRuntime().exec(args.toArray(new String[0]));
quarkusProcess = LauncherUtil.launchProcess(args, env);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class DefaultNativeImageLauncher implements NativeImageLauncher {
private long waitTimeSeconds;
private String testProfile;
private List<String> argLine;
private Map<String, String> env;
private String nativeImagePath;
private String configuredOutputDirectory;
private Class<?> testClass;
Expand All @@ -51,6 +52,7 @@ public void init(NativeImageInitContext initContext) {
this.nativeImagePath = initContext.nativeImagePath();
this.configuredOutputDirectory = initContext.getConfiguredOutputDirectory();
this.argLine = initContext.argLine();
this.env = initContext.env();
this.testClass = initContext.testClass();
}

Expand Down Expand Up @@ -145,9 +147,9 @@ public void start(String[] programArgs, boolean handleIo) throws IOException {
Files.deleteIfExists(logFile);
Files.createDirectories(logFile.getParent());
if (handleIo) {
quarkusProcess = LauncherUtil.launchProcess(args);
quarkusProcess = LauncherUtil.launchProcessAndDrainIO(args, env);
} else {
quarkusProcess = Runtime.getRuntime().exec(args.toArray(new String[0]));
quarkusProcess = LauncherUtil.launchProcess(args, env);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,7 @@ interface DockerInitContext extends InitContext {
boolean pullRequired();

Map<Integer, Integer> additionalExposedPorts();

Map<String, String> labels();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.quarkus.test.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -10,7 +9,9 @@
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
Expand Down Expand Up @@ -57,20 +58,32 @@ public static Config installAndGetSomeConfig() {
* Implementation detail: Avoid using ProcessBuilder's redirect here because it causes problems with Maven Failsafe
* as can be seen in <a href="https://github.com/quarkusio/quarkus/issues/33229">here</a>
*/
static Process launchProcess(List<String> args) throws IOException {
Process process = Runtime.getRuntime().exec(args.toArray(new String[0]));
static Process launchProcessAndDrainIO(List<String> args, Map<String, String> env) throws IOException {
Process process = launchProcess(args, env);
new Thread(new ProcessReader(process.getInputStream())).start();
new Thread(new ProcessReader(process.getErrorStream())).start();
return process;
}

/**
* Launches a process using the supplied arguments and makes sure the process's output is drained to standard out
* Launches a process using the supplied arguments but does drain the IO
*/
static Process launchProcess(List<String> args, File dir) throws IOException {
Process process = Runtime.getRuntime().exec(args.toArray(new String[0]), null, dir);
new Thread(new ProcessReader(process.getInputStream())).start();
new Thread(new ProcessReader(process.getErrorStream())).start();
static Process launchProcess(List<String> args, Map<String, String> env) throws IOException {
Process process;
if (env.isEmpty()) {
process = Runtime.getRuntime().exec(args.toArray(new String[0]));
} else {
Map<String, String> currentEnv = System.getenv();
Map<String, String> finalEnv = new HashMap<>(currentEnv);
finalEnv.putAll(env);
String[] envArray = new String[finalEnv.size()];
int i = 0;
for (var entry : finalEnv.entrySet()) {
envArray[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
process = Runtime.getRuntime().exec(args.toArray(new String[0]), envArray);
}
return process;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ private DefaultNativeImageLauncher createLauncher(Class<?> requiredTestClass) {
ConfigUtil.waitTimeValue(config),
config.getOptionalValue("quarkus.test.native-image-profile", String.class).orElse(null),
ConfigUtil.argLineValue(config),
ConfigUtil.env(config),
new ArtifactLauncher.InitContext.DevServicesLaunchResult() {
@Override
public Map<String, String> properties() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.eclipse.microprofile.config.Config;

import io.smallrye.config.SmallRyeConfig;

public final class ConfigUtil {

private ConfigUtil() {
Expand All @@ -33,6 +36,11 @@ public static List<String> argLineValue(Config config) {
return result;
}

public static Map<String, String> env(Config config) {
return ((SmallRyeConfig) config).getOptionalValues("quarkus.test.env", String.class, String.class)
.orElse(Collections.emptyMap());
}

public static Duration waitTimeValue(Config config) {
return config.getOptionalValue("quarkus.test.wait-time", Duration.class)
.orElseGet(() -> config.getOptionalValue("quarkus.test.jar-wait-time", Duration.class) // legacy value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.time.Duration;
import java.util.List;
import java.util.Map;

import io.quarkus.test.common.ArtifactLauncher;

Expand All @@ -11,15 +12,20 @@ class DefaultInitContextBase {
private final Duration waitTime;
private final String testProfile;
private final List<String> argLine;

private final Map<String, String> env;
private final ArtifactLauncher.InitContext.DevServicesLaunchResult devServicesLaunchResult;

DefaultInitContextBase(int httpPort, int httpsPort, Duration waitTime, String testProfile, List<String> argLine,
DefaultInitContextBase(int httpPort, int httpsPort, Duration waitTime, String testProfile,
List<String> argLine,
Map<String, String> env,
ArtifactLauncher.InitContext.DevServicesLaunchResult devServicesLaunchResult) {
this.httpPort = httpPort;
this.httpsPort = httpsPort;
this.waitTime = waitTime;
this.testProfile = testProfile;
this.argLine = argLine;
this.env = env;
this.devServicesLaunchResult = devServicesLaunchResult;
}

Expand All @@ -43,6 +49,10 @@ public List<String> argLine() {
return argLine;
}

public Map<String, String> env() {
return env;
}

public ArtifactLauncher.InitContext.DevServicesLaunchResult getDevServicesLaunchResult() {
return devServicesLaunchResult;
}
Expand Down
Loading