Skip to content
Open
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
2 changes: 1 addition & 1 deletion dsl/camel-jbang/camel-jbang-plugin-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@

<dependency>
<groupId>org.citrusframework</groupId>
<artifactId>citrus-jbang-connector</artifactId>
<artifactId>citrus-base</artifactId>
<version>${citrus-version}</version>
</dependency>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dsl.jbang.core.commands.test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.commands.ExportHelper;
import org.apache.camel.util.IOHelper;
import org.citrusframework.CitrusVersion;
import picocli.CommandLine;

/**
* Initializes a new Citrus test file from a template. Creates the test subfolder if it does not exist and writes a
* template test source for the given file type. Also creates a jbang.properties file with default Citrus dependencies
* when not already present.
*/
@CommandLine.Command(name = "init",
description = "Initialize a new Citrus test from a template")
public class TestInit extends CamelCommand {

public static final String TEST_DIR = "test";

@CommandLine.Parameters(index = "0", description = "Test file name (e.g. MyTest.yaml, MyTest.xml, MyTest.java)")
String file;

@CommandLine.Option(names = { "-d", "--directory" }, description = "Target directory", defaultValue = ".")
String directory;

public TestInit(CamelJBangMain main) {
super(main);
}

@Override
public Integer doCall() throws Exception {
// Determine file extension and base name
String ext = getFileExtension(file);
String baseName = getBaseName(file);

if (ext.isEmpty()) {
printer().println("Cannot determine file type for: " + file);
return 1;
}

// Load template for the file type
String template;
try (InputStream is = TestInit.class.getClassLoader().getResourceAsStream("templates/citrus-" + ext + ".tmpl")) {
if (is == null) {
printer().println("Unsupported test file type: " + ext);
return 1;
}
template = IOHelper.loadText(is);
}

// Replace template placeholders
template = template.replaceAll("\\{\\{ \\.Name }}", baseName);

// Determine the working directory
Path workingDir = resolveTestDir();
if (workingDir == null) {
printer().println("Cannot create test working directory");
return 1;
}

// Create target directory if specified
Path targetDir;
if (".".equals(directory)) {
targetDir = workingDir;
} else {
targetDir = workingDir.resolve(directory);
Files.createDirectories(targetDir);
}

// Create jbang properties with default dependencies if not present
createJBangProperties(workingDir);

// Write the test file
Path testFile = targetDir.resolve(file);
Files.writeString(testFile, template);

printer().println("Created test file: " + testFile);
return 0;
}

/**
* Resolves and creates the test directory. Automatically uses the test subfolder as the working directory.
*/
private Path resolveTestDir() {
Path currentDir = Paths.get(".");
Path workingDir;
if (TEST_DIR.equals(currentDir.toAbsolutePath().normalize().getFileName().toString())) {
// current directory is already the test subfolder
workingDir = currentDir;
} else if (currentDir.resolve(TEST_DIR).toFile().exists()) {
// navigate to existing test subfolder
workingDir = currentDir.resolve(TEST_DIR);
} else if (currentDir.resolve(TEST_DIR).toFile().mkdirs()) {
// create test subfolder and navigate to it
workingDir = currentDir.resolve(TEST_DIR);
} else {
return null;
}
return workingDir;
}

/**
* Creates jbang.properties with default Citrus dependencies if not already present.
*/
private void createJBangProperties(Path workingDir) {
if (!workingDir.resolve("jbang.properties").toFile().exists()) {
Path jbangProperties = workingDir.resolve("jbang.properties");
try (InputStream is
= TestInit.class.getClassLoader().getResourceAsStream("templates/jbang-properties.tmpl")) {
String context = IOHelper.loadText(is);
context = context.replaceAll("\\{\\{ \\.CitrusVersion }}", CitrusVersion.version());
ExportHelper.safeCopy(new ByteArrayInputStream(context.getBytes(StandardCharsets.UTF_8)), jbangProperties);
} catch (Exception e) {
printer().println("Failed to create jbang.properties for tests in: " + jbangProperties);
}
}
}

private static String getFileExtension(String fileName) {
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
return fileName.substring(dotIndex + 1);
}
return "";
}

private static String getBaseName(String fileName) {
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex > 0) {
return fileName.substring(0, dotIndex);
}
return fileName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,166 +16,28 @@
*/
package org.apache.camel.dsl.jbang.core.commands.test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.camel.RuntimeCamelException;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.commands.ExportHelper;
import org.apache.camel.dsl.jbang.core.common.CamelJBangPlugin;
import org.apache.camel.dsl.jbang.core.common.Plugin;
import org.apache.camel.dsl.jbang.core.common.PluginExporter;
import org.apache.camel.util.IOHelper;
import org.citrusframework.CitrusVersion;
import org.citrusframework.jbang.JBangSettings;
import org.citrusframework.jbang.JBangSupport;
import org.citrusframework.jbang.ProcessAndOutput;
import picocli.CommandLine;

@CamelJBangPlugin(name = "camel-jbang-plugin-test", firstVersion = "4.14.0")
public class TestPlugin implements Plugin {

@Override
public void customize(CommandLine commandLine, CamelJBangMain main) {
commandLine.setExecutionStrategy(new CitrusExecutionStrategy(main))
.addSubcommand("test", new CommandLine(new TestCommand(main))
.setUnmatchedArgumentsAllowed(true)
.setUnmatchedOptionsAllowedAsOptionParameters(true));
var cmd = new CommandLine(new TestCommand(main))
.addSubcommand("init", new CommandLine(new TestInit(main)))
.addSubcommand("run", new CommandLine(new TestRun(main)));

commandLine.addSubcommand("test", cmd);
}

@Override
public Optional<PluginExporter> getExporter() {
return Optional.of(new TestPluginExporter());
}

/**
* Command execution strategy delegates to Citrus JBang for subcommands like init or run. Performs special command
* preparations and makes sure to run the proper Citrus version for this Camel release.
*
* @param main Camel JBang main that provides the output printer.
*/
private record CitrusExecutionStrategy(CamelJBangMain main) implements CommandLine.IExecutionStrategy {

public static final String TEST_DIR = "test";

@Override
public int execute(CommandLine.ParseResult parseResult)
throws CommandLine.ExecutionException, CommandLine.ParameterException {

String command;
List<String> args = Collections.emptyList();

if (parseResult.originalArgs().size() > 2) {
command = parseResult.originalArgs().get(1);
args = parseResult.originalArgs().subList(2, parseResult.originalArgs().size());
} else if (parseResult.originalArgs().size() == 2) {
command = parseResult.originalArgs().get(1);
} else {
// run help command by default
command = "--help";
}

JBangSupport citrus = JBangSupport.jbang().app(JBangSettings.getApp())
.withSystemProperty("citrus.jbang.version", CitrusVersion.version());

// Prepare commands
if ("init".equals(command)) {
return executeInitCommand(citrus, args);
} else if ("run".equals(command)) {
return executeRunCommand(citrus, args);
}

return execute(citrus, command, args);
}

/**
* Prepare and execute init command. Automatically uses test subfolder as a working directory for creating new
* tests. Automatically adds a jbang.properties configuration to add required Camel Citrus dependencies.
*/
private int executeInitCommand(JBangSupport citrus, List<String> args) {
Path currentDir = Paths.get(".");
Path workingDir;
// Automatically set test subfolder as a working directory
if (TEST_DIR.equals(currentDir.getFileName().toString())) {
// current directory is already the test subfolder
workingDir = currentDir;
} else if (currentDir.resolve(TEST_DIR).toFile().exists()) {
// navigate to existing test subfolder
workingDir = currentDir.resolve(TEST_DIR);
citrus.workingDir(workingDir);
} else if (currentDir.resolve(TEST_DIR).toFile().mkdirs()) {
// create test subfolder and navigate to it
workingDir = currentDir.resolve(TEST_DIR);
citrus.workingDir(workingDir);
} else {
throw new RuntimeCamelException("Cannot create test working directory in: " + currentDir);
}

// Create jbang properties with default dependencies if not present
if (!workingDir.resolve("jbang.properties").toFile().exists()) {
Path jbangProperties = workingDir.resolve("jbang.properties");
try (InputStream is
= TestPlugin.class.getClassLoader().getResourceAsStream("templates/jbang-properties.tmpl")) {
String context = IOHelper.loadText(is);

context = context.replaceAll("\\{\\{ \\.CitrusVersion }}", CitrusVersion.version());

ExportHelper.safeCopy(new ByteArrayInputStream(context.getBytes(StandardCharsets.UTF_8)), jbangProperties);
} catch (Exception e) {
main.getOut().println("Failed to create jbang.properties for tests in:" + jbangProperties);
}
}

return execute(citrus, "init", args);
}

/**
* Prepare and execute Citrus run command. Automatically navigates to test subfolder if it is present and uses
* this as a working directory. Runs command asynchronous streaming logs to the main output of this Camel JBang
* process.
*/
private int executeRunCommand(JBangSupport citrus, List<String> args) {
Path currentDir = Paths.get(".");
List<String> runArgs = new ArrayList<>(args);
// automatically navigate to test subfolder for test execution
if (currentDir.resolve(TEST_DIR).toFile().exists()) {
// set test subfolder as working directory
citrus.workingDir(currentDir.resolve(TEST_DIR));

// remove test folder prefix in test file path if present
if (!args.isEmpty() && args.get(0).startsWith(TEST_DIR + "/")) {
runArgs = new ArrayList<>(args.subList(1, args.size()));
runArgs.add(0, args.get(0).substring((TEST_DIR + "/").length()));
}
}

citrus.withOutputListener(output -> main.getOut().print(output));
ProcessAndOutput pao = citrus.runAsync("run", runArgs);
try {
pao.waitFor();
} catch (InterruptedException e) {
main.getOut().printErr("Interrupted while running Citrus command", e);
}

return pao.getProcess().exitValue();
}

/**
* Uses given Citrus JBang instance to run the given command using the given arguments.
*
* @return exit code of the command process.
*/
private int execute(JBangSupport citrus, String command, List<String> args) {
ProcessAndOutput pao = citrus.run(command, args);
main.getOut().print(pao.getOutput());
return pao.getProcess().exitValue();
}
}
}
Loading
Loading