Skip to content

Commit

Permalink
[rewrite] #1281 wip config js much simplified
Browse files Browse the repository at this point in the history
  • Loading branch information
ptrthomas committed Oct 9, 2020
1 parent 92adbb3 commit b27854e
Show file tree
Hide file tree
Showing 25 changed files with 481 additions and 227 deletions.
39 changes: 24 additions & 15 deletions karate-core/src/main/java/com/intuit/karate/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public class FileUtils {
public static final String THIS_COLON = "this:";
public static final String FILE_COLON = "file:";
public static final String SRC_TEST_JAVA = "src/test/java";
public static final String SRC_TEST_RESOURCES = "src/test/resources";
public static final String SRC_TEST_RESOURCES = "src/test/resources";
private static final ClassLoader CLASS_LOADER = FileUtils.class.getClassLoader();

private FileUtils() {
Expand Down Expand Up @@ -323,7 +323,7 @@ public static void writeToFile(File file, byte[] data) {
}
// try with resources, so will be closed automatically
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
fos.write(data);
}
} catch (IOException e) {
throw new RuntimeException(e);
Expand Down Expand Up @@ -452,12 +452,21 @@ public static String toRelativeClassPath(Class clazz) {
}

public static Path fromRelativeClassPath(String relativePath, ClassLoader cl) {
boolean isFile = isFilePath(relativePath);
relativePath = removePrefix(relativePath);
URL url = cl.getResource(relativePath);
if (url == null) {
throw new RuntimeException("file does not exist: " + relativePath);
if (isFile) {
File file = new File(relativePath);
if (!file.exists()) {
throw new RuntimeException("file does not exist: " + relativePath);
}
return file.toPath();
} else { // classpath
URL url = cl.getResource(relativePath);
if (url == null) {
throw new RuntimeException("file does not exist: " + relativePath);
}
return urlToPath(url, relativePath);
}
return urlToPath(url, relativePath);
}

public static Path fromRelativeClassPath(String relativePath, Path parentPath) {
Expand Down Expand Up @@ -488,7 +497,7 @@ public static List<Resource> scanForFeatureFiles(List<String> paths, ClassLoader

public static List<Resource> scanForFeatureFiles(List<String> paths, Class clazz) {
if (clazz == null) {
return scanForFeatureFiles(paths, Thread.currentThread().getContextClassLoader());
return scanForFeatureFiles(paths, ClassLoader.getSystemClassLoader());
}
// this resolves paths relative to the passed-in class
List<Resource> list = new ArrayList();
Expand Down Expand Up @@ -658,11 +667,11 @@ private static void collectFeatureFiles(URL url, String searchPath, List<Resourc
String relativePath = rootPath.relativize(path.toAbsolutePath()).toString();
relativePath = toStandardPath(relativePath).replaceAll("[.]+/", "");
String prefix = classpath ? CLASSPATH_COLON : "";
files.add(new Resource(path, prefix + relativePath, line));
files.add(new Resource(null, path, prefix + relativePath, line));
}
}
}

// TODO use this <Set> based and tighter routine for feature files above
private static void walkPath(Path root, Set<String> results, Predicate<Path> predicate) {
Stream<Path> stream;
Expand All @@ -679,10 +688,10 @@ private static void walkPath(Path root, Set<String> results, Predicate<Path> pre
} catch (IOException e) { // NoSuchFileException
LOGGER.trace("unable to walk path: {} - {}", root, e.getMessage());
}
}
}

private static final Predicate<Path> IS_JS_FILE = p -> p != null && p.toString().endsWith(".js");

public static Set<String> jsFiles(File baseDir) {
Set<String> results = new HashSet();
walkPath(baseDir.toPath().toAbsolutePath(), results, IS_JS_FILE);
Expand All @@ -702,15 +711,15 @@ public static Set<String> jsFiles(String basePath) {
LOGGER.warn("unable to scan for js files at: {}", basePath);
}
return results;
}
}

public static InputStream resourceAsStream(String resourcePath) {
InputStream is = CLASS_LOADER.getResourceAsStream(resourcePath);
if (is == null) {
throw new RuntimeException("failed to read: " + resourcePath);
}
return is;
}
}

public static String getBuildDir() {
String temp = System.getProperty("karate.output.dir");
Expand Down
50 changes: 19 additions & 31 deletions karate-core/src/main/java/com/intuit/karate/Resource.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,55 +46,38 @@ public class Resource {
private final String relativePath;
private final String packageQualifiedName;

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

public static Resource of(Path path, String text) {
return new Resource(path, null, -1) {
final InputStream is = FileUtils.toInputStream(text);

@Override
public InputStream getStream() {
return is;
}
};
}

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

public Resource(Path path, String relativePath, int line) {
public Resource(ClassLoader cl, Path path, String relativePath, int line) {
this.path = path;
this.line = line;
file = !path.toUri().getScheme().equals("jar");
if (relativePath == null) {
this.relativePath = FileUtils.toRelativeClassPath(path, Thread.currentThread().getContextClassLoader());
} else {
this.relativePath = relativePath;
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
relativePath = FileUtils.toRelativeClassPath(path, cl);
}
packageQualifiedName = FileUtils.toPackageQualifiedName(this.relativePath);
this.relativePath = relativePath;
packageQualifiedName = FileUtils.toPackageQualifiedName(relativePath);
}

public Resource(URL url) {
this(FileUtils.urlToPath(url, null));
}

public Resource(Path path) {
this(path, null, -1);
this(null, path, null, -1);
}

public Resource(ClassLoader cl, String relativePath) {
String strippedPath = FileUtils.removePrefix(relativePath);
URL url = cl.getResource(strippedPath);
if (url != null) {
this.path = FileUtils.urlToPath(url, strippedPath);
} else {
this.path = new File(strippedPath).toPath();
}
this.line = -1;
file = !path.toUri().getScheme().equals("jar");
this.relativePath = relativePath;
packageQualifiedName = FileUtils.toPackageQualifiedName(relativePath);
this(FileUtils.fromRelativeClassPath(relativePath, cl));
}

public Resource(String relativePath) {
this(ClassLoader.getSystemClassLoader(), relativePath);
}

public String getFileNameWithoutExtension() {
Expand Down Expand Up @@ -155,4 +138,9 @@ public String toString() {
return relativePath;
}

public static String relativePathToString(String relativePath) {
Resource resource = new Resource(relativePath);
return resource.getAsString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ public class FeatureParser extends KarateParserBaseListener {
private static final List<String> PREFIXES = Arrays.asList("*", "Given", "When", "Then", "And", "But");

public static Feature parse(String relativePath) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Path path = FileUtils.fromRelativeClassPath(relativePath, cl);
return parse(new Resource(path, relativePath, -1));
return parse(new Resource(relativePath));
}

public static Feature parse(File file) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public void testUsingKarateBase() throws Exception {
String relativePath = "classpath:demo/jar1/caller.feature";
ClassLoader cl = getJarClassLoader();
Path path = FileUtils.fromRelativeClassPath(relativePath, cl);
Resource resource = new Resource(path, relativePath, -1);
Resource resource = new Resource(cl, path, relativePath, -1);
Feature feature = FeatureParser.parse(resource);
try {
Map<String, Object> map = Runner.runFeature(feature, null, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.intuit.karate.FileUtils;
import com.intuit.karate.Resource;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
Expand All @@ -16,22 +17,23 @@
public class FeatureEditTest {

private static final Logger logger = LoggerFactory.getLogger(FeatureEditTest.class);


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

private Feature parse(String name) {
InputStream is = getClass().getResourceAsStream(name);
String text = FileUtils.toString(is);
Resource resource = Resource.EMPTY;
return FeatureParser.parseText(new Feature(resource), text);
return FeatureParser.parseText(new Feature(EMPTY), text);
}

private void printLines(List<String> lines) {
int count = lines.size();
for (int i = 0; i < count; i++) {
String line = lines.get(i);
logger.trace("{}: {}", i + 1, line);
logger.trace("{}: {}", i + 1, line);
}
}

@Test
public void testScenario() {
Feature feature = parse("scenario.feature");
Expand All @@ -41,18 +43,18 @@ public void testScenario() {
Background background = feature.getBackground();
Step step = background.getSteps().get(0);
assertEquals("def a = 1", step.getText());

Scenario scenario = feature.getSections().get(0).getScenario();
assertFalse(scenario.isOutline());
assertFalse(scenario.isOutline());
assertEquals(8, scenario.getLine()); // scenario on line 8
List<Step> steps = scenario.getSteps();
assertEquals(3, steps.size());
step = steps.get(0);
assertEquals(9, step.getLine());
step = steps.get(1);
assertEquals(11, step.getLine());
assertEquals(9, step.getLine());
step = steps.get(1);
assertEquals(11, step.getLine());
}

@Test
public void testScenarioOutline() {
Feature feature = parse("outline.feature");
Expand All @@ -63,8 +65,8 @@ public void testScenarioOutline() {
assertEquals(4, so.getScenarios().size());
Scenario scenario = so.getScenarios().get(0);
assertTrue(scenario.isOutline());
}
}

@Test
public void testInsert() {
Feature feature = parse("scenario.feature");
Expand All @@ -73,12 +75,12 @@ public void testInsert() {
assertEquals(17, lines.size());
assertEquals(1, feature.getSections().size());
}

@Test
public void testEdit() {
Feature feature = parse("scenario.feature");
Step step = feature.getSections().get(0).getScenario().getSteps().get(0);
int line = step.getLine();
int line = step.getLine();
feature = feature.replaceLines(line, line, "Then assert 2 == 2");
assertEquals(1, feature.getSections().size());
}
Expand All @@ -99,8 +101,8 @@ public void testMultiLineEditDocString() {
assertEquals("Then assert 2 == 2", feature.getLines().get(10));
assertEquals("Then match b == { foo: 'bar'}", feature.getLines().get(11));
assertEquals(1, feature.getSections().size());
}
}

@Test
public void testMultiLineEditTable() {
Feature feature = parse("table.feature");
Expand All @@ -115,13 +117,12 @@ public void testMultiLineEditTable() {
assertEquals(7, lines.size());
assertEquals("Then assert 2 == 2", feature.getLines().get(3));
assertEquals("* match cats == [{name: 'Bob', age: 2}, {name: 'Wild', age: 4}, {name: 'Nyan', age: 3}]", feature.getLines().get(5));
}
}

@Test
public void testIdentifyingStepWhichIsAnHttpCall() {
String text = "Feature:\nScenario:\n* method post";
Resource resource = Resource.EMPTY;
Feature feature = FeatureParser.parseText(new Feature(resource), text);
Feature feature = FeatureParser.parseText(new Feature(EMPTY), text);
Step step = feature.getSections().get(0).getScenario().getSteps().get(0);
logger.debug("step name: '{}'", step.getText());
assertTrue(step.getText().startsWith("method"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ private boolean macroEqualsExpected(String expStr) {
int closeBracketPos = macro.indexOf(']');
if (closeBracketPos != -1) { // array, match each
if (!actual.isList()) {
return fail("actual is not a list or array");
return fail("actual is not an array");
}
if (closeBracketPos > 1) {
String bracketContents = macro.substring(1, closeBracketPos);
Expand All @@ -244,7 +244,7 @@ private boolean macroEqualsExpected(String expStr) {
}
JsValue jv = jsEngine.eval(sizeExpr);
if (!jv.isTrue()) {
return fail("actual array / list size is " + listSize);
return fail("actual array length is " + listSize);
}
}
if (macro.length() > closeBracketPos + 1) {
Expand Down Expand Up @@ -356,15 +356,15 @@ private boolean actualEqualsExpected() {
int actListCount = actList.size();
int expListCount = expList.size();
if (actListCount != expListCount) {
return fail("actual size is not equal to expected size - " + actListCount + ":" + expListCount);
return fail("actual array length is not equal to expected - " + actListCount + ":" + expListCount);
}
for (int i = 0; i < actListCount; i++) {
MatchValue actListValue = new MatchValue(actList.get(i));
MatchValue expListValue = new MatchValue(expList.get(i));
MatchOperation mo = new MatchOperation(context.descend(i), MatchType.EQUALS, actListValue, expListValue);
mo.execute();
if (!mo.pass) {
return fail("array / list match failed at index " + i);
return fail("array match failed at index " + i);
}
}
return true;
Expand Down Expand Up @@ -466,10 +466,10 @@ private boolean actualContainsExpected() {
int actListCount = actList.size();
int expListCount = expList.size();
if (expListCount > actListCount) {
return fail("actual size is less than expected size - " + actListCount + ":" + expListCount);
return fail("actual array length is less than expected - " + actListCount + ":" + expListCount);
}
if (type == MatchType.CONTAINS_ONLY && expListCount != actListCount) {
return fail("actual size is not equal to expected size - " + actListCount + ":" + expListCount);
return fail("actual array length is not equal to expected - " + actListCount + ":" + expListCount);
}
for (Object exp : expList) { // for each item in the expected list
boolean found = false;
Expand All @@ -494,11 +494,11 @@ private boolean actualContainsExpected() {
}
}
if (!found && type != MatchType.CONTAINS_ANY) { // if we reached here, all items in the actual list were scanned
return fail("actual list does not contain expected item - " + exp);
return fail("actual array does not contain expected item - " + exp);
}
}
if (type == MatchType.CONTAINS_ANY) {
return fail("actual list does not contain any expected item");
return fail("actual array does not contain any of the expected items");
}
return true; // if we reached here, all items in the expected list were found
case MAP:
Expand All @@ -521,7 +521,7 @@ private static BigDecimal toBigDecimal(Object o) {
Number n = (Number) o;
return BigDecimal.valueOf(n.doubleValue());
} else {
throw new RuntimeException("expected number or big-decimal: " + o);
throw new RuntimeException("expected number instead of: " + o);
}
}

Expand Down
Loading

0 comments on commit b27854e

Please sign in to comment.