Skip to content

Commit

Permalink
Handle Karate tests in a BootJar
Browse files Browse the repository at this point in the history
  • Loading branch information
celcius112 committed Jul 22, 2019
1 parent 4b6a931 commit 2b14c2d
Show file tree
Hide file tree
Showing 14 changed files with 249 additions and 50 deletions.
40 changes: 20 additions & 20 deletions karate-core/src/main/java/com/intuit/karate/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public static ScriptValue readFile(String text, ScenarioContext context) {
DocumentContext doc = JsonUtils.fromYaml(contents);
return new ScriptValue(doc, text);
} else {
InputStream is = getFileStream(text, context);
InputStream is = readFileAsStream(text, context);
return new ScriptValue(is, text);
}
}
Expand Down Expand Up @@ -160,21 +160,20 @@ public static Feature parseFeatureAndCallTag(String path) {

private static Resource toResource(String path, ScenarioContext context) {
if (isClassPath(path)) {
ClassLoader cl = context.getClass().getClassLoader();
return new Resource(fromRelativeClassPath(path, cl), path, -1);
return new Resource(context, path);
} else if (isFilePath(path)) {
String temp = removePrefix(path);
return new Resource(new File(temp), path);
} else if (isThisPath(path)) {
String temp = removePrefix(path);
Path parentPath = context.featureContext.parentPath;
Path childPath = parentPath.resolve(temp);
return new Resource(childPath, path, -1);
return new Resource(context, childPath);
} else {
try {
Path parentPath = context.rootFeatureContext.parentPath;
Path childPath = parentPath.resolve(path);
return new Resource(childPath, path, -1);
return new Resource(context, childPath);
} catch (Exception e) {
logger.error("feature relative path resolution failed: {}", e.getMessage());
throw e;
Expand All @@ -183,21 +182,23 @@ private static Resource toResource(String path, ScenarioContext context) {
}

public static String readFileAsString(String path, ScenarioContext context) {
return toString(readFileAsStream(path, context));
}

public static InputStream readFileAsStream(String path, ScenarioContext context) {
try {
InputStream is = getFileStream(path, context);
return toString(is);
return toResource(path, context).getStream();
} catch (Exception e) {
String message = String.format("could not find or read file: %s", path);
context.logger.trace("{}", message);
throw new KarateFileNotFoundException(message);
InputStream inputStream = context.getResourceAsStream(removePrefix(path));
if (inputStream == null) {
String message = String.format("could not find or read file: %s", path);
context.logger.trace("{}", message);
throw new KarateFileNotFoundException(message);
}
return inputStream;
}
}

public static InputStream getFileStream(String path, ScenarioContext context) {
Resource fr = toResource(path, context);
return fr.getStream();
}

public static String toPackageQualifiedName(String path) {
path = removePrefix(path);
path = path.replace('/', '.');
Expand Down Expand Up @@ -599,7 +600,7 @@ private static void collectFeatureFiles(URL url, String searchPath, List<Resourc
} catch (IOException e) { // NoSuchFileException
return;
}
for (Iterator<Path> paths = stream.iterator(); paths.hasNext();) {
for (Iterator<Path> paths = stream.iterator(); paths.hasNext(); ) {
Path path = paths.next();
Path fileName = path.getFileName();
if (fileName != null && fileName.toString().endsWith(".feature")) {
Expand Down Expand Up @@ -634,11 +635,11 @@ public static boolean isOsWindows() {
public static boolean isOsMacOsX() {
return getOsType() == OsType.MACOSX;
}

public static String getOsName() {
return System.getProperty("os.name");
}

public static OsType getOsType() {
return getOsType(getOsName());
}
Expand All @@ -648,7 +649,7 @@ public static OsType getOsType(String name) {
name = "unknown";
} else {
name = name.toLowerCase();
}
}
if (name.contains("win")) {
return OsType.WINDOWS;
} else if (name.contains("mac")) {
Expand All @@ -659,5 +660,4 @@ public static OsType getOsType(String name) {
return OsType.UNKNOWN;
}
}

}
41 changes: 35 additions & 6 deletions karate-core/src/main/java/com/intuit/karate/Resource.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
*/
package com.intuit.karate;

import com.intuit.karate.core.ScenarioContext;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand All @@ -40,17 +42,23 @@
public class Resource {

private final boolean file;
private final Path path;
private final Path path;
private final int line;
private final String relativePath;
private final String packageQualifiedName;

private URL url;

public static final Resource EMPTY = new Resource(Paths.get(""), "", -1);

public Resource(File file, String relativePath) {
this(file.toPath(), relativePath, -1);
}

public Resource(URL url, String relativePath, int line) {
this(Paths.get(url.getPath()), relativePath, line);
this.url = url;
}

public Resource(Path path, String relativePath, int line) {
this.path = path;
this.line = line;
Expand All @@ -59,10 +67,29 @@ public Resource(Path path, String relativePath, int line) {
packageQualifiedName = FileUtils.toPackageQualifiedName(relativePath);
}

public Resource(ScenarioContext sc, Path path) {
this(sc, path.normalize().toString());
}

public Resource(ScenarioContext sc, String relativePath) {
String strippedPath = FileUtils.removePrefix(relativePath);
URL resource = sc.getResource(strippedPath);
if (resource != null) {
this.url = resource;
this.path = Paths.get(resource.getPath());
} else {
this.path = new File(strippedPath).toPath();
}
this.line = -1;
file = !path.toUri().getScheme().equals("jar");
this.relativePath = relativePath;
packageQualifiedName = FileUtils.toPackageQualifiedName(relativePath);
}

public String getFileNameWithoutExtension() {
return FileUtils.removeFileExtension(path.getFileName().toString());
}

public String getRelativePath() {
return relativePath;
}
Expand All @@ -73,17 +100,19 @@ public String getPackageQualifiedName() {

public Path getPath() {
return path;
}
}

public int getLine() {
return line;
}
}

private static final Map<String, byte[]> STREAM_CACHE = new HashMap();

public InputStream getStream() {
try {
if (file) {
if (url != null) {
return url.openStream();
} else if (file) {
return new FileInputStream(path.toFile());
} else {
byte[] bytes = STREAM_CACHE.get(relativePath);
Expand Down
16 changes: 8 additions & 8 deletions karate-core/src/main/java/com/intuit/karate/Runner.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ public static Results parallel(String reportDir, int threadCount, String ... tag
return parallel(tags, paths, threadCount, reportDir);
}

public static Results parallel(List<String> tags, List<String> paths, String scenarioName,
Collection<ExecutionHook> hooks, int threadCount, String reportDir) {
public static Results parallel(List<String> tags, List<String> paths, String scenarioName,
Collection<ExecutionHook> hooks, int threadCount, String reportDir) {
String tagSelector = tags == null ? null : Tags.fromKarateOptionsTags(tags);
List<Resource> files = FileUtils.scanForFeatureFiles(paths, Thread.currentThread().getContextClassLoader());
return parallel(tagSelector, files, scenarioName, hooks, threadCount, reportDir);
Expand All @@ -94,8 +94,8 @@ public static Results parallel(String tagSelector, List<Resource> resources, int
return parallel(tagSelector, resources, null, null, threadCount, reportDir);
}

public static Results parallel(String tagSelector, List<Resource> resources, String scenarioName,
Collection<ExecutionHook> hooks, int threadCount, String reportDir) {
public static Results parallel(String tagSelector, List<Resource> resources, String scenarioName,
Collection<ExecutionHook> hooks, int threadCount, String reportDir) {
if (threadCount < 1) {
threadCount = 1;
}
Expand All @@ -106,7 +106,7 @@ public static Results parallel(String tagSelector, List<Resource> resources, Str
final String finalReportDir = reportDir;
// logger.info("Karate version: {}", FileUtils.getKarateVersion());
Results results = Results.startTimer(threadCount);
ExecutorService featureExecutor = Executors.newFixedThreadPool(threadCount);
ExecutorService featureExecutor = Executors.newFixedThreadPool(threadCount, Executors.privilegedThreadFactory());
ExecutorService scenarioExecutor = Executors.newWorkStealingPool(threadCount);
int executedFeatureCount = 0;
try {
Expand All @@ -122,7 +122,7 @@ public static Results parallel(String tagSelector, List<Resource> resources, Str
FeatureContext featureContext = new FeatureContext(null, feature, tagSelector);
CallContext callContext = CallContext.forAsync(feature, hooks, null, false);
ExecutionContext execContext = new ExecutionContext(results.getStartTime(), featureContext, callContext, reportDir,
r -> featureExecutor.submit(r), scenarioExecutor);
r -> featureExecutor.submit(r), scenarioExecutor, Thread.currentThread().getContextClassLoader());
featureResults.add(execContext.result);
FeatureExecutionUnit unit = new FeatureExecutionUnit(execContext);
unit.setNext(() -> {
Expand All @@ -131,8 +131,8 @@ public static Results parallel(String tagSelector, List<Resource> resources, Str
File file = Engine.saveResultJson(finalReportDir, result, null);
if (result.getScenarioCount() < 500) {
// TODO this routine simply cannot handle that size
Engine.saveResultXml(finalReportDir, result, null);
}
Engine.saveResultXml(finalReportDir, result, null);
}
String status = result.isFailed() ? "fail" : "pass";
logger.info("<<{}>> feature {} of {}: {}", status, index, count, feature.getRelativePath());
result.printStats(file.getPath());
Expand Down
17 changes: 10 additions & 7 deletions karate-core/src/main/java/com/intuit/karate/StepActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ public class StepActions implements Actions {
public final ScenarioContext context;

public StepActions(FeatureContext featureContext, CallContext callContext, Scenario scenario, Logger logger) {
context = new ScenarioContext(featureContext, callContext, scenario, logger);
this(featureContext, callContext, null, scenario, logger);
}

public StepActions(FeatureContext featureContext, CallContext callContext, ClassLoader classLoader, Scenario scenario, Logger logger) {
context = new ScenarioContext(featureContext, callContext, classLoader, scenario, logger);
}

public StepActions(ScenarioContext context) {
Expand Down Expand Up @@ -367,25 +371,24 @@ public void eval(String exp) {
public void evalDocstring(String exp) {
context.eval(exp);
}

@Override
@When("^([\\w]+)([^\\s^\\w])(.+)")
public void eval(String name, String dotOrParen, String expression) {
context.eval(name + dotOrParen + expression);
}
}

@Override
@When("^if (.+)")
public void evalIf(String exp) {
context.eval("if " + exp);
}

}
//==========================================================================
//

@Override
@When("^driver (.+)")
public void driver(String expression) {
context.driver(expression);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,23 @@ public class ExecutionContext {
public final FeatureResult result;
public final Consumer<Runnable> system;
public final ExecutorService scenarioExecutor;
public final ClassLoader classLoader;

private final File reportDir;

public ExecutionContext(long startTime, FeatureContext featureContext, CallContext callContext, String reportDirString,
Consumer<Runnable> system, ExecutorService scenarioExecutor) {
Consumer<Runnable> system, ExecutorService scenarioExecutor) {
this(startTime, featureContext, callContext, reportDirString, system, scenarioExecutor, null);
}

public ExecutionContext(long startTime, FeatureContext featureContext, CallContext callContext, String reportDirString,
Consumer<Runnable> system, ExecutorService scenarioExecutor, ClassLoader classLoader) {
this.scenarioExecutor = scenarioExecutor;
this.startTime = startTime;
result = new FeatureResult(featureContext.feature);
this.featureContext = featureContext;
this.callContext = callContext;
this.classLoader = classLoader;
if (callContext.perfMode) {
reportDir = null;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.intuit.karate.StringUtils;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -56,8 +57,8 @@ public FeatureContext(String envString, Feature feature, File workingDir, String
this.env = getEnv(envString);
this.tagSelector = tagSelector;
this.feature = feature;
this.callCache = new HashMap(1);
this.parentPath = workingDir == null ? feature.getPath().getParent() : workingDir.toPath();
this.callCache = new HashMap(1);
this.parentPath = workingDir == null ? Paths.get(feature.getRelativePath()).getParent() : workingDir.toPath();
this.packageQualifiedName = workingDir == null ? feature.getResource().getPackageQualifiedName() : "";
}

Expand Down
Loading

0 comments on commit 2b14c2d

Please sign in to comment.