diff options
Diffstat (limited to 'javaparser-testing/src/test/java')
149 files changed, 15818 insertions, 0 deletions
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java new file mode 100644 index 000000000..c44a63f50 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/CommentsInserterTest.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.comments.CommentsCollection; +import org.junit.Test; + +import java.io.IOException; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class CommentsInserterTest { + private String makeFilename(String sampleName) { + return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt"; + } + + private ParseResult<CompilationUnit> parseSample(String sampleName) throws IOException { + Provider p = Providers.resourceProvider( + makeFilename(sampleName)); + return new JavaParser().parse(ParseStart.COMPILATION_UNIT, p); + } + + /** + * Issue: "When there is a String constant "\\" compilationUnit ignores all further comments" + */ + @Test + public void issue290() throws IOException { + ParseResult result = parseSample("Issue290"); + CommentsCollection cc = (CommentsCollection) result.getCommentsCollection().get(); + assertEquals(1, cc.getLineComments().size()); + assertEquals(1, cc.getJavadocComments().size()); + } + + @Test + public void issue624() throws IOException { + parseResource(makeFilename("Issue624")); + // Should not fail + } + + @Test + public void issue200EnumConstantsWithCommentsForceVerticalAlignment() { + CompilationUnit cu = parse("public enum X {" + EOL + + " /** const1 javadoc */" + EOL + + " BORDER_CONSTANT," + EOL + + " /** const2 javadoc */" + EOL + + " ANOTHER_CONSTANT" + EOL + + "}"); + assertEqualsNoEol("public enum X {\n" + + "\n" + + " /**\n" + + " * const1 javadoc\n" + + " */\n" + + " BORDER_CONSTANT,\n" + + " /**\n" + + " * const2 javadoc\n" + + " */\n" + + " ANOTHER_CONSTANT\n" + + "}\n", cu.toString()); + } + + @Test + public void issue234LosingCommentsInArrayInitializerExpr() { + CompilationUnit cu = parse("@Anno(stuff={" + EOL + + " // Just," + EOL + + " // an," + EOL + + " // example" + EOL + + "})" + EOL + + "class ABC {" + EOL + + "" + EOL + + "}"); + + assertEqualsNoEol("@Anno(stuff = {// Just,\n" + + "// an,\n" + + "// example\n" + + "})\n" + + "class ABC {\n" + + "}\n", cu.toString()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java b/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java new file mode 100644 index 000000000..fdecede5c --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/GeneratedJavaParserTokenManagerTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import org.junit.Test; + +import java.io.IOException; + +public class GeneratedJavaParserTokenManagerTest { + private String makeFilename(String sampleName) { + return "com/github/javaparser/issue_samples/" + sampleName + ".java.txt"; + } + + @Test + public void issue1003() throws IOException { + JavaParser.parseResource(makeFilename("issue1003")); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java new file mode 100644 index 000000000..7302e953f --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/JavaParserTest.java @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.CastExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.LambdaExpr; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.IntersectionType; +import com.github.javaparser.ast.type.Type; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Optional; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JavaParserTest { + + @Test + public void rangeOfAnnotationMemberDeclarationIsCorrect() { + String code = "@interface AD { String foo(); }"; + CompilationUnit cu = JavaParser.parse(code); + AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + assertEquals(true, memberDeclaration.getRange().isPresent()); + assertEquals(new Range(new Position(1, 17), new Position(1, 29)), memberDeclaration.getRange().get()); + } + + @Test + public void rangeOfAnnotationMemberDeclarationWithArrayTypeIsCorrect() { + String code = "@interface AD { String[] foo(); }"; + CompilationUnit cu = JavaParser.parse(code); + AnnotationMemberDeclaration memberDeclaration = cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + assertEquals(true, memberDeclaration.getRange().isPresent()); + assertEquals(new Range(new Position(1, 17), new Position(1, 31)), memberDeclaration.getRange().get()); + } + + @Test + public void rangeOfArrayCreationLevelWithExpressionIsCorrect() { + String code = "new int[123][456]"; + ArrayCreationExpr expression = JavaParser.parseExpression(code); + Optional<Range> range; + + range = expression.getLevels().get(0).getRange(); + assertEquals(true, range.isPresent()); + assertEquals(new Range(new Position(1, 8), new Position(1, 12)), range.get()); + + range = expression.getLevels().get(1).getRange(); + assertEquals(true, range.isPresent()); + assertEquals(new Range(new Position(1, 13), new Position(1, 17)), range.get()); + } + + @Test + public void rangeOfArrayCreationLevelWithoutExpressionIsCorrect() { + String code = "new int[][]"; + ArrayCreationExpr expression = JavaParser.parseExpression(code); + Optional<Range> range; + + range = expression.getLevels().get(0).getRange(); + assertEquals(true, range.isPresent()); + assertEquals(new Range(new Position(1, 8), new Position(1, 9)), range.get()); + + range = expression.getLevels().get(1).getRange(); + assertEquals(true, range.isPresent()); + assertEquals(new Range(new Position(1, 10), new Position(1, 11)), range.get()); + } + + @Test + public void parseErrorContainsLocation() { + ParseResult<CompilationUnit> result = new JavaParser().parse(COMPILATION_UNIT, provider("class X { // blah")); + + Problem problem = result.getProblem(0); + assertEquals(range(1, 9, 1, 17), problem.getLocation().get().toRange().get()); + assertEquals("Parse error. Found <EOF>, expected one of \";\" \"<\" \"@\" \"abstract\" \"boolean\" \"byte\" \"char\" \"class\" \"default\" \"double\" \"enum\" \"exports\" \"final\" \"float\" \"int\" \"interface\" \"long\" \"module\" \"native\" \"open\" \"opens\" \"private\" \"protected\" \"provides\" \"public\" \"requires\" \"short\" \"static\" \"strictfp\" \"synchronized\" \"to\" \"transient\" \"transitive\" \"uses\" \"void\" \"volatile\" \"with\" \"{\" \"}\" <IDENTIFIER>", problem.getMessage()); + assertInstanceOf(ParseException.class, problem.getCause().get()); + } + + @Test + public void parseIntersectionType() { + String code = "(Runnable & Serializable) (() -> {})"; + Expression expression = JavaParser.parseExpression(code); + Type type = expression.asCastExpr().getType(); + + assertTrue(type instanceof IntersectionType); + IntersectionType intersectionType = type.asIntersectionType(); + assertEquals(2, intersectionType.getElements().size()); + assertTrue(intersectionType.getElements().get(0) instanceof ClassOrInterfaceType); + assertEquals("Runnable", intersectionType.getElements().get(0).asClassOrInterfaceType().getNameAsString()); + assertTrue(intersectionType.getElements().get(1) instanceof ClassOrInterfaceType); + assertEquals("Serializable", intersectionType.getElements().get(1).asClassOrInterfaceType().getNameAsString()); + } + + @Test + public void rangeOfIntersectionType() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + Type type = castExpr.getType(); + assertEquals(range(3, 13, 3, 54), type.getRange().get()); + } + + @Test + public void rangeOfCast() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + assertEquals(range(3, 12, 3, 101), castExpr.getRange().get()); + } + + @Test + public void rangeOfCastNonIntersection() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> )(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + assertEquals(range(3, 12, 3, 101), castExpr.getRange().get()); + } + + @Test + public void rangeOfLambda() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + assertEquals(range(3, 56, 3, 101), lambdaExpr.getRange().get()); + assertEquals(GeneratedJavaParserConstants.LPAREN, lambdaExpr.getTokenRange().get().getBegin().getKind()); + assertEquals(GeneratedJavaParserConstants.RPAREN, lambdaExpr.getTokenRange().get().getEnd().getKind()); + } + + @Test + public void rangeOfLambdaBody() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + ReturnStmt returnStmt = methodDeclaration.getBody().get().getStatement(0).asReturnStmt(); + CastExpr castExpr = returnStmt.getExpression().get().asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + Statement lambdaBody = lambdaExpr.getBody(); + assertEquals(range(3, 68, 3, 101), lambdaBody.getRange().get()); + } + + @Test + public void testNotStoringTokens() { + JavaParser javaParser = new JavaParser(new ParserConfiguration().setStoreTokens(false)); + ParseResult<CompilationUnit> result = javaParser.parse(ParseStart.COMPILATION_UNIT, provider("class X{}")); + assertEquals(false, result.getTokens().isPresent()); + } + + @Test(expected = ParseProblemException.class) + public void trailingCodeIsAnError() { + JavaParser.parseBlock("{} efijqoifjqefj"); + } + + @Test + public void trailingWhitespaceIsIgnored() { + BlockStmt blockStmt = JavaParser.parseBlock("{} // hello"); + assertEquals("{}", blockStmt.getTokenRange().get().toString()); + } + + @Test + public void everyTokenHasACategory() throws IOException { + final int tokenCount = GeneratedJavaParserConstants.tokenImage.length; + Path tokenTypesPath = mavenModuleRoot(JavaParserTest.class).resolve("../javaparser-core/src/main/java/com/github/javaparser/TokenTypes.java"); + CompilationUnit tokenTypesCu = JavaParser.parse(tokenTypesPath); + // -1 to take off the default: case. + int switchEntries = tokenTypesCu.findAll(SwitchEntryStmt.class).size()-1; + // The amount of "case XXX:" in TokenTypes.java should be equal to the amount of tokens JavaCC knows about: + assertEquals(tokenCount, switchEntries); + } + + @Test + public void parsingInitializedAndUnitializedVarsInForStmt() { + ForStmt forStmt = JavaParser.parseStatement("for(int a,b=0;;){}").asForStmt(); + assertEquals(1, forStmt.getInitialization().size()); + assertEquals(true, forStmt.getInitialization().get(0).isVariableDeclarationExpr()); + assertEquals(2, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().size()); + assertEquals("a", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getNameAsString()); + assertEquals("b", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getNameAsString()); + assertEquals(false, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent()); + assertEquals(true, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent()); + } + + @Test + public void parsingInitializedAndUnitializedVarsInForStmtComplexCase() { + // See issue 1281 + ForStmt forStmt = JavaParser.parseStatement("for(int i, j = array2.length - 1;;){}").asForStmt(); + assertEquals(1, forStmt.getInitialization().size()); + assertEquals(true, forStmt.getInitialization().get(0).isVariableDeclarationExpr()); + assertEquals(2, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().size()); + assertEquals("i", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getNameAsString()); + assertEquals("j", forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getNameAsString()); + assertEquals(false, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(0).getInitializer().isPresent()); + assertEquals(true, forStmt.getInitialization().get(0).asVariableDeclarationExpr().getVariables().get(1).getInitializer().isPresent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java new file mode 100644 index 000000000..e69a76ab0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/JavaTokenTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import com.github.javaparser.ast.expr.Expression; +import org.junit.Test; + +import java.util.Iterator; + +import static com.github.javaparser.GeneratedJavaParserConstants.*; +import static com.github.javaparser.JavaToken.Category.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JavaTokenTest { + + @Test + public void testAFewTokens() { + ParseResult<Expression> result = new JavaParser().parse(ParseStart.EXPRESSION, provider("1 +/*2*/1 ")); + Iterator<JavaToken> iterator = result.getResult().get().getTokenRange().get().iterator(); + assertToken("1", range(1, 1, 1, 1), INTEGER_LITERAL, LITERAL, iterator.next()); + assertToken(" ", range(1, 2, 1, 2), SPACE, WHITESPACE_NO_EOL, iterator.next()); + assertToken("+", range(1, 3, 1, 3), PLUS, OPERATOR, iterator.next()); + assertToken("/*2*/", range(1, 4, 1, 8), MULTI_LINE_COMMENT, COMMENT, iterator.next()); + assertToken("1", range(1, 9, 1, 9), INTEGER_LITERAL, LITERAL, iterator.next()); + assertToken(" ", range(1, 10, 1, 10), SPACE, WHITESPACE_NO_EOL, iterator.next()); + assertToken("", range(1, 10, 1, 10), EOF, WHITESPACE_NO_EOL, iterator.next()); + assertEquals(false, iterator.hasNext()); + } + + private void assertToken(String image, Range range, int kind, JavaToken.Category category, JavaToken token) { + assertEquals(image, token.getText()); + assertEquals(range, token.getRange().get()); + assertEquals(kind, token.getKind()); + assertEquals(category, token.getCategory()); + token.getNextToken().ifPresent(nt -> assertEquals(token, nt.getPreviousToken().get())); + token.getPreviousToken().ifPresent(pt -> assertEquals(token, pt.getNextToken().get())); + assertTrue(token.getNextToken().isPresent() || token.getPreviousToken().isPresent()); + } + + @Test + public void testAFewImagesForTokenKinds() { + assertEquals("=", new JavaToken(ASSIGN).getText()); + // TODO this shouldn't be a space. + assertEquals(" ", new JavaToken(EOF).getText()); + assertEquals("*/", new JavaToken(JAVADOC_COMMENT).getText()); + } + + @Test + public void testKindEnum() { + JavaToken.Kind kind = JavaToken.Kind.valueOf(GeneratedJavaParserConstants.ASSERT); + + assertEquals(JavaToken.Kind.ASSERT, kind); + assertEquals(GeneratedJavaParserConstants.ASSERT, kind.getKind()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java b/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java new file mode 100644 index 000000000..99e138e21 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/JavadocParserTest.java @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.JavadocBlockTag; +import com.github.javaparser.javadoc.description.JavadocDescription; +import org.junit.Assert; +import org.junit.Test; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class JavadocParserTest { + + @Test + public void parseSimplestContent() { + Assert.assertEquals(new Javadoc(JavadocDescription.parseText("A simple line of text")), + JavadocParser.parse("A simple line of text")); + } + + @Test + public void parseSingleLineWithSpacing() { + assertEquals(new Javadoc(JavadocDescription.parseText("The line number of the first character of this Token.")), + JavadocParser.parse(" The line number of the first character of this Token. ")); + } + + @Test + public void parseSingleLineWithNewLines() { + assertEquals(new Javadoc(JavadocDescription.parseText("The string image of the token.")), + JavadocParser.parse(EOL + + " * The string image of the token." + EOL + + " ")); + } + + @Test + public void parseCommentWithNewLines() { + String text = EOL + + " * The version identifier for this Serializable class." + EOL + + " * Increment only if the <i>serialized</i> form of the" + EOL + + " * class changes." + EOL + + " "; + assertEquals(new Javadoc(JavadocDescription.parseText("The version identifier for this Serializable class." + EOL + + "Increment only if the <i>serialized</i> form of the" + EOL + + "class changes.")), + JavadocParser.parse(text)); + } + + @Test + public void parseCommentWithIndentation() { + String text = "Returns a new Token object, by default." + EOL + + " * However, if you want, you can create and return subclass objects based on the value of ofKind." + EOL + + " *" + EOL + + " * case MyParserConstants.ID : return new IDToken(ofKind, image);" + EOL + + " *" + EOL + + " * to the following switch statement. Then you can cast matchedToken"; + assertEquals(new Javadoc(JavadocDescription.parseText("Returns a new Token object, by default." + EOL + + "However, if you want, you can create and return subclass objects based on the value of ofKind." + EOL + + EOL + + " case MyParserConstants.ID : return new IDToken(ofKind, image);" + EOL + + EOL + + "to the following switch statement. Then you can cast matchedToken")), + JavadocParser.parse(text)); + } + + @Test + public void parseBlockTagsAndEmptyDescription() { + String text = EOL + + " * @deprecated" + EOL + + " * @see #getEndColumn" + EOL + + " "; + assertEquals(new Javadoc(JavadocDescription.parseText("")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.DEPRECATED, "")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.SEE, "#getEndColumn")), JavadocParser.parse(text)); + } + + @Test + public void parseBlockTagsAndProvideTagName() { + String expectedText = EOL + + " * @unofficial" + EOL + " " + + " "; + + Javadoc underTest = new Javadoc(JavadocDescription.parseText("")) + .addBlockTag(new JavadocBlockTag("unofficial", "")); + + + assertEquals(underTest, JavadocParser.parse(expectedText)); + assertEquals(1, underTest.getBlockTags().size()); + assertEquals("unofficial", underTest.getBlockTags().get(0).getTagName()); + } + + @Test + public void parseParamBlockTags() { + String text = EOL + + " * Add a field to this and automatically add the import of the type if needed" + EOL + + " *" + EOL + + " * @param typeClass the type of the field" + EOL + + " * @param name the name of the field" + EOL + + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + EOL + + " * @return the {@link FieldDeclaration} created" + EOL + + " "; + Javadoc res = JavadocParser.parse(text); + assertEquals(new Javadoc(JavadocDescription.parseText("Add a field to this and automatically add the import of the type if needed")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("typeClass", "the type of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("modifiers", "the modifiers like {@link Modifier#PUBLIC}")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")), res); + } + + @Test + public void parseMultilineParamBlockTags() { + String text = EOL + + " * Add a field to this and automatically add the import of the type if needed" + EOL + + " *" + EOL + + " * @param typeClass the type of the field" + EOL + + " * continued in a second line" + EOL + + " * @param name the name of the field" + EOL + + " * @param modifiers the modifiers like {@link Modifier#PUBLIC}" + EOL + + " * @return the {@link FieldDeclaration} created" + EOL + + " "; + Javadoc res = JavadocParser.parse(text); + assertEquals(new Javadoc(JavadocDescription.parseText("Add a field to this and automatically add the import of the type if needed")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("typeClass", "the type of the field" + EOL + " continued in a second line")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("name", "the name of the field")) + .addBlockTag(JavadocBlockTag.createParamBlockTag("modifiers", "the modifiers like {@link Modifier#PUBLIC}")) + .addBlockTag(new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "the {@link FieldDeclaration} created")), res); + } + + @Test + public void startsWithAsteriskEmpty() { + assertEquals(-1, JavadocParser.startsWithAsterisk("")); + } + + @Test + public void startsWithAsteriskNoAsterisk() { + assertEquals(-1, JavadocParser.startsWithAsterisk(" ciao")); + } + + @Test + public void startsWithAsteriskAtTheBeginning() { + assertEquals(0, JavadocParser.startsWithAsterisk("* ciao")); + } + + @Test + public void startsWithAsteriskAfterSpaces() { + assertEquals(3, JavadocParser.startsWithAsterisk(" * ciao")); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java new file mode 100644 index 000000000..b41c28bf4 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ParseErrorRecoveryTest.java @@ -0,0 +1,42 @@ +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.LabeledStmt; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE; +import static org.junit.Assert.assertEquals; + +public class ParseErrorRecoveryTest { + private final JavaParser parser = new JavaParser(); + + @Test + public void compilationUnitRecovery() { + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("XXX")).getResult().get(); + assertEquals(UNPARSABLE, cu.getParsed()); + } + + @Test + public void bodystatementSemicolonRecovery() { + MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X;}")).getResult().get().asMethodDeclaration(); + Statement xxx = cu.getBody().get().getStatements().get(0); + assertEquals(UNPARSABLE, xxx.getParsed()); + } + + @Test + public void bodystatementClosingBraceRecovery() { + MethodDeclaration cu = parser.parse(ParseStart.CLASS_BODY, provider("int x(){X X X}")).getResult().get().asMethodDeclaration(); + Statement xxx = cu.getBody().get(); + assertEquals(UNPARSABLE, xxx.getParsed()); + } + + @Test + public void labeledStatementSemicolonRecovery() { + CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, provider("class X{int x(){aaa:X X X;}}")).getResult().get(); + LabeledStmt xxx = cu.getClassByName("X").get().getMethods().get(0).getBody().get().getStatements().get(0).asLabeledStmt(); + assertEquals(UNPARSABLE, xxx.getStatement().getParsed()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java new file mode 100644 index 000000000..abc400912 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ParserConfigurationTest.java @@ -0,0 +1,33 @@ +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ParserConfigurationTest { + @Test + public void storeNoTokens() { + ParseResult<CompilationUnit> result = new JavaParser(new ParserConfiguration().setStoreTokens(false)).parse(ParseStart.COMPILATION_UNIT, provider("class X{}")); + + assertFalse(result.getResult().get().getTokenRange().isPresent()); + assertTrue(result.getResult().get().findAll(Node.class).stream().noneMatch(node -> node.getTokenRange().isPresent())); + } + + @Test + public void noProblemsHere() { + ParseResult<Statement> result = + new JavaParser(new ParserConfiguration().setLanguageLevel(RAW)) + .parse(STATEMENT, provider("try{}")); + assertEquals(true, result.isSuccessful()); + } + + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java new file mode 100644 index 000000000..0654344ba --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ProblemTest.java @@ -0,0 +1,32 @@ +package com.github.javaparser; + +import org.junit.Test; + +import static com.github.javaparser.Range.range; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.Assert.assertEquals; + +public class ProblemTest { + @Test + public void testSimpleGetters() { + Problem problem = new Problem("Parse error", TokenRange.INVALID, new Exception()); + + assertEquals(TokenRange.INVALID, problem.getLocation().get()); + assertEquals("Parse error", problem.getMessage()); + assertInstanceOf(Exception.class, problem.getCause().get()); + } + + @Test + public void testVerboseMessage() { + Problem problem = new Problem("Parse error", TokenRange.INVALID, null); + + assertEquals("(line ?,col ?) Parse error", problem.getVerboseMessage()); + } + + @Test + public void testVerboseMessageWithoutLocation() { + Problem problem = new Problem("Parse error", null, null); + + assertEquals("Parse error", problem.getVerboseMessage()); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java new file mode 100644 index 000000000..14b351af9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ProvidersTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.Charset; + +import static org.junit.Assert.*; + +public class ProvidersTest { + + @Test + public void testResourceProvider() throws IOException { + Provider provider = Providers.resourceProvider("com/github/javaparser/issue_samples/Issue290.java.txt"); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + } + + @Test + public void testResourceProviderWithWrongEncoding() throws IOException { + Provider provider = Providers.resourceProvider("com/github/javaparser/TestFileIso88591.java"); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertFalse(parse.isSuccessful()); + } + + @Test + public void testResourceProviderWithEncoding() throws IOException { + Provider provider = Providers.resourceProvider( + "com/github/javaparser/TestFileIso88591.java", + Charset.forName("ISO-8859-1") + ); + assertNotNull(provider); + JavaParser parser = new JavaParser(); + ParseResult<CompilationUnit> parse = parser.parse(ParseStart.COMPILATION_UNIT, provider); + assertTrue(parse.isSuccessful()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java new file mode 100644 index 000000000..1d2b49ade --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/RangeTest.java @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class RangeTest { + + @Test + public void aRangeContainsItself() throws IOException { + Range r = Range.range(1, 1, 3, 10); + assertEquals(true, r.contains(r)); + } + + @Test + public void aRangeDoesNotStrictlyContainsItself() throws IOException { + Range r = Range.range(1, 1, 3, 10); + assertEquals(false, r.strictlyContains(r)); + } + + @Test + public void overlappingButNotContainedRangesAreNotOnContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(2, 1, 7, 10); + assertEquals(false, r1.contains(r2)); + assertEquals(false, r2.contains(r1)); + } + + @Test + public void overlappingButNotContainedRangesAreNotOnStrictlyContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(2, 1, 7, 10); + assertEquals(false, r1.strictlyContains(r2)); + assertEquals(false, r2.strictlyContains(r1)); + } + + @Test + public void unrelatedRangesAreNotOnContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(5, 1, 7, 10); + assertEquals(false, r1.contains(r2)); + assertEquals(false, r2.contains(r1)); + } + + @Test + public void unrelatedRangesAreNotOnStrictlyContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(5, 1, 7, 10); + assertEquals(false, r1.strictlyContains(r2)); + assertEquals(false, r2.strictlyContains(r1)); + } + + @Test + public void strictlyContainedRangesOnContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(2, 1, 3, 4); + assertEquals(true, r1.contains(r2)); + assertEquals(false, r2.contains(r1)); + } + + @Test + public void strictlyContainedRangesOnStrictlyContains() throws IOException { + Range r1 = Range.range(1, 1, 3, 10); + Range r2 = Range.range(2, 1, 3, 4); + assertEquals(true, r1.strictlyContains(r2)); + assertEquals(false, r2.strictlyContains(r1)); + } + + @Test + public void containsConsiderLines() { + Range r1 = Range.range(22, 9, 22, 29); + Range r2 = Range.range(26, 19, 26, 28); + assertEquals(false, r1.contains(r2)); + assertEquals(false, r2.contains(r1)); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java new file mode 100644 index 000000000..d067c8e1f --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/TokenRangeTest.java @@ -0,0 +1,14 @@ +package com.github.javaparser; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TokenRangeTest { + @Test + public void toStringWorks() { + CompilationUnit cu = JavaParser.parse("class X {\n\tX(){\n// hello\n}\n}"); + assertEquals("X(){\n// hello\n}", cu.getClassByName("X").get().getDefaultConstructor().get().getTokenRange().get().toString()); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java new file mode 100644 index 000000000..ec17e39b7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/CompilationUnitTest.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.JavaParser; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.utils.CodeGenerationUtils.mavenModuleRoot; +import static org.junit.Assert.assertEquals; + +public class CompilationUnitTest { + @Test + public void issue578TheFirstCommentIsWithinTheCompilationUnit() { + CompilationUnit compilationUnit = parse("// This is my class, with my comment\n" + + "class A {\n" + + " static int a;\n" + + "}"); + + assertEquals(1, compilationUnit.getAllContainedComments().size()); + } + + @Test + public void testGetSourceRoot() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "Z.java")); + + CompilationUnit cu = parse(testFile); + Path sourceRoot1 = cu.getStorage().get().getSourceRoot(); + assertEquals(sourceRoot, sourceRoot1); + } + + @Test(expected = RuntimeException.class) + public void testGetSourceRootWithBadPackageDeclaration() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "A.java")); + + CompilationUnit cu = parse(testFile); + cu.getStorage().get().getSourceRoot(); + } + + @Test + public void testGetSourceRootInDefaultPackage() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources", "com", "github", "javaparser", "storage")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("B.java")); + + CompilationUnit cu = parse(testFile); + Path sourceRoot1 = cu.getStorage().get().getSourceRoot(); + assertEquals(sourceRoot, sourceRoot1); + } + + @Test + public void testGetPrimaryTypeName() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java")); + CompilationUnit cu = JavaParser.parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryTypeName().get()); + } + + @Test + public void testNoPrimaryTypeName() { + CompilationUnit cu = JavaParser.parse("class PrimaryType{}"); + + assertEquals(false, cu.getPrimaryTypeName().isPresent()); + } + @Test + public void testGetPrimaryType() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType.java")); + CompilationUnit cu = JavaParser.parse(testFile); + + assertEquals("PrimaryType", cu.getPrimaryType().get().getNameAsString()); + } + + @Test + public void testNoPrimaryType() throws IOException { + Path sourceRoot = mavenModuleRoot(CompilationUnitTest.class).resolve(Paths.get("src", "test", "resources")).normalize(); + Path testFile = sourceRoot.resolve(Paths.get("com", "github", "javaparser", "storage", "PrimaryType2.java")); + CompilationUnit cu = JavaParser.parse(testFile); + + assertEquals(false, cu.getPrimaryType().isPresent()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java new file mode 100644 index 000000000..91163650a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/DataKeyTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class DataKeyTest { + public static final DataKey<String> ABC = new DataKey<String>() { + }; + public static final DataKey<List<String>> LISTY = new DataKey<List<String>>() { + }; + public static final DataKey<List<String>> DING = new DataKey<List<String>>() { + }; + + @Test + public void addAFewKeysAndSeeIfTheyAreStoredCorrectly() { + Node node = new SimpleName(); + + node.setData(ABC, "Hurray!"); + node.setData(LISTY, Arrays.asList("a", "b")); + node.setData(ABC, "w00t"); + + assertThat(node.getData(ABC)).contains("w00t"); + assertThat(node.getData(LISTY)).containsExactly("a", "b"); + assertThat(node.getData(DING)).isNull(); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java new file mode 100644 index 000000000..8e4d568bd --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeListTest.java @@ -0,0 +1,329 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.observer.AstObserver; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import java.util.Arrays; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; + +import static com.github.javaparser.ast.NodeList.nodeList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeListTest { + + private AstObserver createObserver(List<String> changes) { + return new AstObserver() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("change of property %s for %s: from '%s' to '%s'", property, observedNode, oldValue, newValue)); + } + + @Override + public void parentChange(Node observedNode, Node previousParent, Node newParent) { + changes.add(String.format("setting parent for %s: was %s, now is %s", observedNode, previousParent, newParent)); + } + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add(String.format("'%s' %s in list at %d", nodeAddedOrRemoved, type, index)); + } + + @Override + public void listReplacement(NodeList observedNode, int index, Node oldNode, Node newNode) { + changes.add(String.format("'%s' %s in list at %d", oldNode, ListChangeType.REMOVAL, index)); + changes.add(String.format("'%s' %s in list at %d", newNode, ListChangeType.ADDITION, index)); + } + }; + } + + private FieldDeclaration createIntField(String name) { + return new FieldDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), name); + } + + @Test + public void addAllWithoutIndex() { + List<String> changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().addAll(Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c"))); + assertEquals(Arrays.asList("'int a;' ADDITION in list at 1", + "'int b;' ADDITION in list at 2", + "'int c;' ADDITION in list at 3"), changes); + } + + @Test + public void addAllWithIndex() { + List<String> changes = new LinkedList<>(); + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().addAll(0, Arrays.asList(createIntField("a"), createIntField("b"), createIntField("c"))); + assertEquals(Arrays.asList("'int a;' ADDITION in list at 0", + "'int b;' ADDITION in list at 1", + "'int c;' ADDITION in list at 2"), changes); + } + + @Test + public void clear() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().clear(); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0", + "'int b;' REMOVAL in list at 0", + "'int c;' REMOVAL in list at 0"), changes); + } + + @Test + public void set() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().set(1, createIntField("d")); + assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1", + "'int d;' ADDITION in list at 1"), changes); + } + + @Test + public void removeNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove(cd.getFieldByName("c").get()); + assertEquals(Arrays.asList("'int c;' REMOVAL in list at 2"), changes); + } + + @Test + public void removeFirstNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeFirst(); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0"), changes); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertTrue(cd.getMembers().removeFirst() != null); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + public void removeLastNode() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeLast(); + assertEquals(Arrays.asList("'int e;' REMOVAL in list at 4"), changes); + assertEquals(cd.getMembers().size(), 4); + + for (int i = 3; i >= 0; i--) { + assertTrue(cd.getMembers().removeLast() != null); + assertEquals(cd.getMembers().size(), i); + } + + assertEquals(cd.getMembers().size(), 0); + } + + @Test + public void removeObject() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().remove("hi"); + assertEquals(Arrays.asList(), changes); + } + + @Test + public void removeAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeAll(Arrays.asList(cd.getFieldByName("b").get(), "foo", cd.getFieldByName("d").get())); + assertEquals(Arrays.asList("'int b;' REMOVAL in list at 1", + "'int d;' REMOVAL in list at 2"), changes); + } + + @Test + public void retainAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; int d; int e; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().retainAll(Arrays.asList(cd.getFieldByName("b").get(), "foo", cd.getFieldByName("d").get())); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0", + "'int c;' REMOVAL in list at 1", + "'int e;' REMOVAL in list at 2"), changes); + } + + @Test + public void replaceAll() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int b; int c; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().replaceAll(bodyDeclaration -> { + FieldDeclaration clone = (FieldDeclaration) bodyDeclaration.clone(); + SimpleName id = clone.getVariable(0).getName(); + id.setIdentifier(id.getIdentifier().toUpperCase()); + return clone; + }); + assertEquals(Arrays.asList("'int a;' REMOVAL in list at 0", "'int A;' ADDITION in list at 0", + "'int b;' REMOVAL in list at 1", "'int B;' ADDITION in list at 1", + "'int c;' REMOVAL in list at 2", "'int C;' ADDITION in list at 2"), changes); + } + + @Test + public void removeIf() { + List<String> changes = new LinkedList<>(); + String code = "class A { int a; int longName; int c; }"; + CompilationUnit cu = JavaParser.parse(code); + ClassOrInterfaceDeclaration cd = cu.getClassByName("A").get(); + cd.getMembers().register(createObserver(changes)); + + cd.getMembers().removeIf(m -> ((FieldDeclaration) m).getVariable(0).getName().getIdentifier().length() > 3); + assertEquals(Arrays.asList("'int longName;' REMOVAL in list at 1"), changes); + } + + @Test + public void replace() { + final NodeList<Name> list = nodeList(new Name("a"), new Name("b"), new Name("c")); + + final boolean replaced = list.replace(new Name("b"), new Name("z")); + + assertEquals(true, replaced); + assertEquals(3, list.size()); + assertEquals("a", list.get(0).asString()); + assertEquals("z", list.get(1).asString()); + assertEquals("c", list.get(2).asString()); + } + + @Test + public void toStringTest() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + assertEquals("[abc, bcd, cde]", list.toString()); + } + + @Test + public void addFirst() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addFirst(new Name("xxx")); + + assertEquals("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + public void addLast() { + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), new Name("cde")); + + list.addLast(new Name("xxx")); + + assertEquals("[abc, bcd, cde, xxx]", list.toString()); + } + + @Test + public void addBefore() { + Name n = new Name("bcd"); + final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde")); + + list.addBefore(new Name("xxx"), n); + + assertEquals("[abc, xxx, bcd, cde]", list.toString()); + } + + @Test + public void addAfter() { + Name n = new Name("bcd"); + final NodeList<Name> list = nodeList(new Name("abc"), n, new Name("cde")); + + list.addAfter(new Name("xxx"), n); + + assertEquals("[abc, bcd, xxx, cde]", list.toString()); + } + + @Test + public void addBeforeFirst() { + Name abc = new Name("abc"); + final NodeList<Name> list = nodeList(abc, new Name("bcd"), new Name("cde")); + + list.addBefore(new Name("xxx"), abc); + + assertEquals("[xxx, abc, bcd, cde]", list.toString()); + } + + @Test + public void addAfterLast() { + Name cde = new Name("cde"); + final NodeList<Name> list = nodeList(new Name("abc"), new Name("bcd"), cde); + + list.addAfter(new Name("xxx"), cde); + + assertEquals("[abc, bcd, cde, xxx]", list.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java new file mode 100644 index 000000000..5ce116de6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodePositionTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.*; +import org.junit.Test; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class NodePositionTest { + + private List<Node> getAllNodes(Node node) { + List<Node> nodes = new LinkedList<>(); + nodes.add(node); + node.getChildNodes().forEach(c -> nodes.addAll(getAllNodes(c))); + return nodes; + } + + @Test + public void packageProtectedClassShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("class A { }"); + } + + @Test + public void packageProtectedInterfaceShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("interface A { }"); + } + + @Test + public void packageProtectedEnumShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("enum A { }"); + } + + @Test + public void packageProtectedAnnotationShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("@interface A { }"); + } + + @Test + public void packageProtectedFieldShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { int i; }"); + } + + @Test + public void packageProtectedMethodShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { void foo() {} }"); + } + + @Test + public void packageProtectedConstructorShouldHavePositionSet() throws IOException { + ensureAllNodesHaveValidBeginPosition("public class A { A() {} }"); + } + + private void ensureAllNodesHaveValidBeginPosition(final String code) throws IOException { + ParseResult<CompilationUnit> res = new JavaParser().parse(ParseStart.COMPILATION_UNIT, Providers.provider(code)); + assertTrue(res.getProblems().isEmpty()); + + CompilationUnit cu = res.getResult().get(); + getAllNodes(cu).forEach(n -> { + assertNotNull(String.format("There should be no node without a range: %s (class: %s)", + n, n.getClass().getCanonicalName()), n.getRange()); + if (n.getBegin().get().line == 0 && !n.toString().isEmpty()) { + throw new IllegalArgumentException("There should be no node at line 0: " + n + " (class: " + + n.getClass().getCanonicalName() + ")"); + } + }); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java new file mode 100644 index 000000000..3201b2910 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/NodeTest.java @@ -0,0 +1,414 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.observer.AstObserver; +import com.github.javaparser.ast.observer.AstObserverAdapter; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.*; + +public class NodeTest { + + @Test + public void registerSubTree() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.registerForSubtree(observer); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"), changes); + } + + @Test + public void registerWithJustNodeMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.JUST_THIS_NODE); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + } + + @Test + public void registerWithNodeAndExistingDescendantsMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.THIS_NODE_AND_EXISTING_DESCENDANTS); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"), changes); + + cu.getClassByName("MyCoolClass").get().addField("int", "bar").getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"), changes); + } + + @Test + public void registerWithSelfPropagatingMode() { + String code = "class A { int f; void foo(int p) { return 'z'; }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.getClassByName("A").get().register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + assertEquals(Arrays.asList(), changes); + + cu.getClassByName("A").get().setName("MyCoolClass"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass"), changes); + + cu.getClassByName("MyCoolClass").get().getFieldByName("f").get().getVariable(0).setType(new PrimitiveType(PrimitiveType.Primitive.BOOLEAN)); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean"), changes); + + cu.getClassByName("MyCoolClass").get().getMethodsByName("foo").get(0).getParameterByName("p").get().setName("myParam"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam"), changes); + + cu.getClassByName("MyCoolClass").get() + .addField("int", "bar") + .getVariables().get(0).setInitializer("0"); + assertEquals(Arrays.asList("ClassOrInterfaceDeclaration.name changed from A to MyCoolClass", + "FieldDeclaration.maximum_common_type changed from int to boolean", + "VariableDeclarator.type changed from int to boolean", + "Parameter.name changed from p to myParam", + "VariableDeclarator.initializer changed from null to 0"), changes); + } + + @Test + public void deleteAParameterTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + cu.getClassByName("A").get().getMethodsByName("foo").get(0).getParameter(0).remove(); + assertEquals(Arrays.asList("removing [int p] from index 0"), changes); + } + + @Test + public void deleteClassNameDoesNotTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + // I cannot remove the name of a type + assertEquals(false, cu.getClassByName("A").get().getName().remove()); + assertEquals(Arrays.asList(), changes); + } + + @Test + public void deleteMethodBodyDoesTriggerNotifications() { + String code = "class A { void foo(int p) { }}"; + CompilationUnit cu = parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new AstObserverAdapter() { + + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add("setting [" + property + "] to " + newValue); + } + + @Override + public void listChange(NodeList observedNode, ListChangeType type, int index, Node nodeAddedOrRemoved) { + changes.add("removing [" + nodeAddedOrRemoved + "] from index " + index); + } + }; + cu.register(observer, Node.ObserverRegistrationMode.SELF_PROPAGATING); + + assertEquals(true, cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get().remove()); + assertEquals(Arrays.asList("setting [BODY] to null"), changes); + } + + @Test + public void removeOrphanCommentPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + Comment c = new LineComment("A comment"); + decl.addOrphanComment(c); + assertEquals(1, decl.getOrphanComments().size()); + assertTrue(decl == c.getParentNode().get()); + assertTrue(decl.removeOrphanComment(c)); + assertEquals(0, decl.getOrphanComments().size()); + assertFalse(c.getParentNode().isPresent()); + } + + @Test + public void removeOrphanCommentNegativeCase() { + ClassOrInterfaceDeclaration aClass = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + FieldDeclaration aField = new FieldDeclaration(EnumSet.noneOf(Modifier.class), new VariableDeclarator(PrimitiveType.intType(), "f")); + aClass.getMembers().add(aField); + Comment c = new LineComment("A comment"); + aField.addOrphanComment(c); + // the comment is an orphan comment of the field, so trying to remove it on the class should not work + assertFalse(aClass.removeOrphanComment(c)); + assertEquals(1, aField.getOrphanComments().size()); + assertTrue(c.getParentNode().isPresent()); + } + + @Test + public void hasJavaDocCommentPositiveCaseWithSetJavaDocComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setJavadocComment("A comment"); + assertEquals(true, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentPositiveCaseWithSetComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertEquals(true, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseLineComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new LineComment("foo")); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public void hasJavaDocCommentNegativeCaseBlockComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new BlockComment("foo")); + assertEquals(false, decl.hasJavaDocComment()); + } + + @Test + public void removeAllOnRequiredProperty() { + CompilationUnit cu = parse("class X{ void x(){}}"); + MethodDeclaration methodDeclaration = cu.getType(0).getMethods().get(0); + methodDeclaration.getName().removeForced(); + // Name is required, so to remove it the whole method is removed. + assertEquals(String.format("class X {%1$s}%1$s", EOL), cu.toString()); + } + + @Test + public void removingTheSecondOfAListOfIdenticalStatementsDoesNotMessUpTheParents() { + CompilationUnit unit = parse(String.format("public class Example {%1$s" + + " public static void example() {%1$s" + + " boolean swapped;%1$s" + + " swapped=false;%1$s" + + " swapped=false;%1$s" + + " }%1$s" + + "}%1$s", EOL)); + // remove the second swapped=false + Node target = unit.getChildNodes().get(0).getChildNodes().get(1).getChildNodes().get(2).getChildNodes().get(2); + target.remove(); + // This will throw an exception if the parents are bad. + System.out.println(unit.toString()); + } + + @Test + public void findCompilationUnit() { + CompilationUnit cu = parse("class X{int x;}"); + VariableDeclarator x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariables().get(0); + assertEquals(cu, x.findCompilationUnit().get()); + } + + @Test + public void findParent() { + CompilationUnit cu = parse("class X{int x;}"); + SimpleName x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariables().get(0).getName(); + assertEquals("int x;", x.findParent(FieldDeclaration.class).get().toString()); + } + + @Test + public void cantFindCompilationUnit() { + VariableDeclarator x = new VariableDeclarator(); + assertFalse(x.findCompilationUnit().isPresent()); + } + + @Test + public void genericWalk() { + Expression e = parseExpression("1+1"); + StringBuilder b = new StringBuilder(); + e.walk(n -> b.append(n.toString())); + assertEquals("1 + 111", b.toString()); + } + + @Test + public void classSpecificWalk() { + Expression e = parseExpression("1+1"); + StringBuilder b = new StringBuilder(); + e.walk(IntegerLiteralExpr.class, n -> b.append(n.toString())); + assertEquals("11", b.toString()); + } + + @Test + public void conditionalFindAll() { + Expression e = parseExpression("1+2+3"); + List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class, n -> n.asInt() > 1); + assertEquals("[2, 3]", ints.toString()); + } + + @Test + public void typeOnlyFindAll() { + Expression e = parseExpression("1+2+3"); + List<IntegerLiteralExpr> ints = e.findAll(IntegerLiteralExpr.class); + assertEquals("[1, 2, 3]", ints.toString()); + } + + @Test + public void typeOnlyFindAllMatchesSubclasses() { + Expression e = parseExpression("1+2+3"); + List<Node> ints = e.findAll(Node.class); + assertEquals("[1 + 2 + 3, 1 + 2, 1, 2, 3]", ints.toString()); + } + + @Test + public void conditionalTypedFindFirst() { + Expression e = parseExpression("1+2+3"); + Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class, n -> n.asInt() > 1); + assertEquals("Optional[2]", ints.toString()); + } + + @Test + public void typeOnlyFindFirst() { + Expression e = parseExpression("1+2+3"); + Optional<IntegerLiteralExpr> ints = e.findFirst(IntegerLiteralExpr.class); + assertEquals("Optional[1]", ints.toString()); + } + + @Test + public void stream() { + Expression e = parseExpression("1+2+3"); + List<IntegerLiteralExpr> ints = e.stream() + .filter(n -> n instanceof IntegerLiteralExpr) + .map(IntegerLiteralExpr.class::cast) + .filter(i -> i.asInt() > 1) + .collect(Collectors.toList()); + assertEquals("[2, 3]", ints.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java new file mode 100644 index 000000000..45d7725bc --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ParseResultTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.Node.Parsedness.PARSED; +import static com.github.javaparser.ast.Node.Parsedness.UNPARSABLE; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.Assertions.assertThat; + +public class ParseResultTest { + private final JavaParser javaParser = new JavaParser(new ParserConfiguration()); + + @Test + public void whenParsingSucceedsThenWeGetResultsAndNoProblems() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{}")); + + assertThat(result.getResult().isPresent()).isTrue(); + assertThat(result.getResult().get().getParsed()).isEqualTo(PARSED); + assertThat(result.getProblems()).isEmpty(); + assertThat(result.getTokens().isPresent()).isTrue(); + + assertThat(result.toString()).isEqualTo("Parsing successful"); + } + + @Test + public void whenParsingFailsThenWeGetProblemsAndABadResult() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class {")); + + assertThat(result.getResult().isPresent()).isTrue(); + assertThat(result.getResult().get().getParsed()).isEqualTo(UNPARSABLE); + assertThat(result.getProblems().size()).isEqualTo(1); + + Problem problem = result.getProblem(0); + assertThat(problem.getMessage()).isEqualTo("Parse error. Found \"{\", expected one of \"enum\" \"exports\" \"module\" \"open\" \"opens\" \"provides\" \"requires\" \"strictfp\" \"to\" \"transitive\" \"uses\" \"with\" <IDENTIFIER>"); + assertThat(result.getTokens().isPresent()).isTrue(); + + assertThat(result.toString()).startsWith("Parsing failed:" + EOL + "(line 1,col 1) Parse error."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java new file mode 100644 index 000000000..4e93efce6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/ReplaceNodeTest.java @@ -0,0 +1,32 @@ +package com.github.javaparser.ast; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parsePackageDeclaration; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ReplaceNodeTest { + @Test + public void testSimplePropertyWithGenericReplace() { + CompilationUnit cu = parse("package x; class Y {}"); + cu.replace(cu.getPackageDeclaration().get(), parsePackageDeclaration("package z;")); + assertEquals(String.format("package z;%1$s" + + "%1$s" + + "class Y {%1$s" + + "}%1$s", EOL), cu.toString()); + } + + @Test + public void testListProperty() { + CompilationUnit cu = parse("package x; class Y {}"); + cu.replace(cu.getClassByName("Y").get(), parse("class B{int y;}").getClassByName("B").get()); + assertEquals(String.format("package x;%1$s" + + "%1$s" + + "class B {%1$s" + + "%1$s" + + " int y;%1$s" + + "}%1$s", EOL), cu.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java new file mode 100644 index 000000000..e133b501b --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/AnnotationMemberDeclarationTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.body; + +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class AnnotationMemberDeclarationTest { + + @Test + public void whenSettingNameTheParentOfNameIsAssigned() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + assertTrue(name.getParentNode().isPresent()); + assertTrue(decl == name.getParentNode().get()); + } + + @Test + public void removeDefaultValueWhenNoDefaultValueIsPresent() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + + decl.removeDefaultValue(); + + assertFalse(decl.getDefaultValue().isPresent()); + } + + @Test + public void removeDefaultValueWhenDefaultValueIsPresent() { + AnnotationMemberDeclaration decl = new AnnotationMemberDeclaration(); + SimpleName name = new SimpleName("foo"); + decl.setName(name); + Expression defaultValue = new IntegerLiteralExpr("2"); + decl.setDefaultValue(defaultValue); + + decl.removeDefaultValue(); + + assertFalse(defaultValue.getParentNode().isPresent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java new file mode 100644 index 000000000..52c77f13c --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ClassOrInterfaceDeclarationTest.java @@ -0,0 +1,60 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ClassOrInterfaceDeclarationTest { + @Test + public void staticNestedClass() { + CompilationUnit cu = JavaParser.parse("class X{static class Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertFalse(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + public void nestedInterface() { + CompilationUnit cu = JavaParser.parse("class X{interface Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertFalse(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + public void nonStaticNestedClass() { + CompilationUnit cu = JavaParser.parse("class X{class Y{}}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get().getMembers().get(0).asClassOrInterfaceDeclaration(); + + assertTrue(y.isInnerClass()); + assertTrue(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + public void topClass() { + CompilationUnit cu = JavaParser.parse("class X{}"); + ClassOrInterfaceDeclaration y = cu.getClassByName("X").get(); + + assertFalse(y.isInnerClass()); + assertFalse(y.isNestedType()); + assertFalse(y.isLocalClassDeclaration()); + } + + @Test + public void localClass() { + MethodDeclaration method= (MethodDeclaration)JavaParser.parseBodyDeclaration("void x(){class X{};}"); + ClassOrInterfaceDeclaration x = method.findFirst(ClassOrInterfaceDeclaration.class).get(); + + assertFalse(x.isInnerClass()); + assertFalse(x.isNestedType()); + assertTrue(x.isLocalClassDeclaration()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java new file mode 100644 index 000000000..34d3b6254 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/ConstructorDeclarationTest.java @@ -0,0 +1,23 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.CLASS_BODY; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ConstructorDeclarationTest { + @Test + public void acceptsSuper() { + ConstructorDeclaration cons = new ConstructorDeclaration("Cons"); + cons.createBody().addStatement("super();"); + + assertEquals(String.format("public Cons() {%1$s" + + " super();%1$s" + + "}", EOL), cons.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java new file mode 100644 index 000000000..0e263a481 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/FieldDeclarationTest.java @@ -0,0 +1,24 @@ +package com.github.javaparser.ast.body; + +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parse; +import static org.junit.Assert.assertEquals; + +public class FieldDeclarationTest { + @Test + public void wofjweoifj() { + CompilationUnit compilationUnit = parse("" + + "class A {\n" + + " int a, b;\n" + + "}"); + + BodyDeclaration<?> declaration = compilationUnit.getType(0).getMembers().get(0); + FieldDeclaration fieldDeclaration = declaration.asFieldDeclaration(); + VariableDeclarator var1 = fieldDeclaration.getVariables().get(0); + VariableDeclarator var2 = fieldDeclaration.getVariables().get(1); + assertEquals(var1, var1.getType().getParentNode().get()); + assertEquals(var2, var2.getType().getParentNode().get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java new file mode 100644 index 000000000..1cbab66ad --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/body/MethodDeclarationTest.java @@ -0,0 +1,87 @@ +package com.github.javaparser.ast.body; + +import org.junit.Ignore; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseBodyDeclaration; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; + +public class MethodDeclarationTest { + @Test + public void annotationsAllowedAfterGenericsAndBeforeReturnType() { + parseBodyDeclaration("public <T> @Abc String method() {return null;}"); + } + + @Test + public void annotationsAllowedBeforeGenerics() { + parseBodyDeclaration("public @Abc <T> String method() {return null;}"); + } + + @Test + public void explicitReceiverParameters1() { + MethodDeclaration method = parseBodyDeclaration("void InnerInner(@mypackage.Anno Source.@mypackage.Anno Inner Source.Inner.this) { }").asMethodDeclaration(); + assertEquals("Source.Inner.this", method.getReceiverParameter().get().getNameAsString()); + } + + @Test + public void explicitReceiverParameters2() { + MethodDeclaration method = parseBodyDeclaration("void x(A this) { }").asMethodDeclaration(); + assertEquals("this", method.getReceiverParameter().get().getNameAsString()); + } + + @Test + public void explicitReceiverParameters3() { + MethodDeclaration method = parseBodyDeclaration("void x(A that) { }").asMethodDeclaration(); + assertFalse(method.getReceiverParameter().isPresent()); + } + + @Test + public void signaturesEqual() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(String z);").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesEqualWhenGenericsDiffer() { + MethodDeclaration method1 = parseBodyDeclaration("void x(List<Long> a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("void x(List<Integer> a) { }").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesEqualWhenAnnotationsDiffer() { + MethodDeclaration method1 = parseBodyDeclaration("void x(@A @B List a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("void x(@C List a) { }").asMethodDeclaration(); + assertEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesDifferentName() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int y(String z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesDifferentTypes() { + MethodDeclaration method1 = parseBodyDeclaration("void x(String a) { }").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signaturesDifferentVarargs() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z);").asMethodDeclaration(); + MethodDeclaration method2 = parseBodyDeclaration("int x(int... z);").asMethodDeclaration(); + assertNotEquals(method1.getSignature(), method2.getSignature()); + } + + @Test + public void signatureToString() { + MethodDeclaration method1 = parseBodyDeclaration("int x(int z, String q);").asMethodDeclaration(); + assertEquals("x(int, String)", method1.getSignature().toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java new file mode 100644 index 000000000..946b76ac1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/comments/CommentTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.comments; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.expr.Name; +import org.junit.Test; + +import java.util.EnumSet; + +import static com.github.javaparser.JavaParser.parse; +import static com.github.javaparser.JavaParser.parseName; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CommentTest { + + @Test + public void removeOrphanComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + Comment c = new LineComment("A comment"); + decl.addOrphanComment(c); + assertEquals(1, decl.getOrphanComments().size()); + assertTrue(c.remove()); + assertEquals(0, decl.getOrphanComments().size()); + } + + @Test + public void removeAssociatedComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), false, "A"); + Comment c = new LineComment("A comment"); + decl.setComment(c); + assertEquals(true, decl.getComment().isPresent()); + assertTrue(c.remove()); + assertEquals(false, decl.getComment().isPresent()); + } + + @Test + public void cannotRemoveCommentNotUsedAnywhere() { + Comment c = new LineComment("A comment"); + assertFalse(c.remove()); + } + + @Test + public void unicodeEscapesArePreservedInComments() { + CompilationUnit cu = parse("// xxx\\u2122xxx"); + Comment comment = cu.getAllContainedComments().get(0); + assertEquals(" xxx\\u2122xxx", comment.getContent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java new file mode 100644 index 000000000..55e87f5e5 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/AssignExprTest.java @@ -0,0 +1,12 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class AssignExprTest { + @Test + public void convertOperator() { + assertEquals(BinaryExpr.Operator.PLUS, AssignExpr.Operator.PLUS.toBinaryOperator().get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java new file mode 100644 index 000000000..9975ef307 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/BinaryExprTest.java @@ -0,0 +1,12 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BinaryExprTest { + @Test + public void convertOperator() { + assertEquals(AssignExpr.Operator.PLUS, BinaryExpr.Operator.PLUS.toAssignOperator().get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java new file mode 100644 index 000000000..9c5464394 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/DoubleLiteralExprTest.java @@ -0,0 +1,37 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; + +public class DoubleLiteralExprTest { + @Test + public void test1() { + float x = 0x0.00_00_02p-126f; + parseExpression("0x0.00_00_02p-126f"); + } + + @Test + public void test2() { + double x = 0x0.000_000_000_000_1p-1_022; + parseExpression("0x0.000_000_000_000_1p-1_022"); + } + + @Test + public void test3() { + double a = 0x1.p+1; + parseExpression("0x1.p+1"); + } + + @Test + public void test4() { + double a = 0x.0p0; + parseExpression("0x.0p0"); + } + + @Test + public void test5() { + double x = 0x0_0.0_0p-1_0; + parseExpression("0x0_0.0_0p-1_0"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java new file mode 100644 index 000000000..0d8a5b9a7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/InstanceOfExprTest.java @@ -0,0 +1,15 @@ +package com.github.javaparser.ast.expr; + +import com.github.javaparser.JavaParser; +import org.junit.Test; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +public class InstanceOfExprTest { + @Test + public void annotationsOnTheType() { + InstanceOfExpr expr = JavaParser.parseExpression("s instanceof @A @DA String"); + + assertThat(expr.getType().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A"), new MarkerAnnotationExpr("DA")); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java new file mode 100644 index 000000000..082906b15 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LambdaExprTest.java @@ -0,0 +1,41 @@ +package com.github.javaparser.ast.expr; + +import com.github.javaparser.TokenRange; +import com.github.javaparser.ast.Node; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static org.junit.Assert.*; + +public class LambdaExprTest { + @Test + public void lambdaRange1(){ + Expression expression = parseExpression("x -> y"); + assertRange("x", "y", expression); + } + + @Test + public void lambdaRange2(){ + Expression expression = parseExpression("(x) -> y"); + assertRange("(", "y", expression); + } + + private void assertRange(String startToken, String endToken, Node node) { + TokenRange tokenRange = node.getTokenRange().get(); + assertEquals(startToken, tokenRange.getBegin().asString()); + assertEquals(endToken, tokenRange.getEnd().asString()); + } + + @Test + public void getExpressionBody(){ + LambdaExpr lambdaExpr = parseExpression("x -> y").asLambdaExpr(); + assertEquals("Optional[y]", lambdaExpr.getExpressionBody().toString()); + } + + @Test + public void getNoExpressionBody(){ + LambdaExpr lambdaExpr = parseExpression("x -> {y;}").asLambdaExpr(); + assertEquals("Optional.empty", lambdaExpr.getExpressionBody().toString()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java new file mode 100644 index 000000000..1b9dfef1a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/LiteralStringValueExprTest.java @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ +package com.github.javaparser.ast.expr; + +import com.github.javaparser.JavaParser; +import org.assertj.core.data.Percentage; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static org.assertj.core.api.Assertions.assertThat; + +@SuppressWarnings("OctalInteger") +public class LiteralStringValueExprTest { + + @Test + public void trivialLiteralsAreConverted() { + assertThat(new CharLiteralExpr('\t').getValue()).isEqualTo("\\t"); + assertThat(new CharLiteralExpr('\b').getValue()).isEqualTo("\\b"); + assertThat(new CharLiteralExpr('\f').getValue()).isEqualTo("\\f"); + assertThat(new CharLiteralExpr('\r').getValue()).isEqualTo("\\r"); + assertThat(new CharLiteralExpr('\n').getValue()).isEqualTo("\\n"); + assertThat(new CharLiteralExpr('\\').getValue()).isEqualTo("\\\\"); + assertThat(new CharLiteralExpr('\"').getValue()).isEqualTo("\\\""); + + assertThat(new IntegerLiteralExpr("0B0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0b0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0X0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr("0x0").asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(00).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0B0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0b0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0X0).asInt()).isEqualTo(0); + assertThat(new IntegerLiteralExpr(0x0).asInt()).isEqualTo(0); + + assertThat(new LongLiteralExpr("0B0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0b0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0X0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr("0x0L").asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(00L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0B0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0b0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0X0L).asLong()).isEqualTo(0); + assertThat(new LongLiteralExpr(0x0L).asLong()).isEqualTo(0); + + assertThat(new DoubleLiteralExpr("0.0f").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0F").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0d").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr("0.0D").asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0F).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0f).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0D).asDouble()).isEqualTo(0.0); + assertThat(new DoubleLiteralExpr(0.0d).asDouble()).isEqualTo(0.0); + } + + @Test + public void lowerAndUpperBoundIntegersAreConverted() { + IntegerLiteralExpr dec = parseExpression("2147483647"); + IntegerLiteralExpr posOct = parseExpression("0177_7777_7777"); + IntegerLiteralExpr negOct = parseExpression("0377_7777_7777"); + IntegerLiteralExpr posHex = parseExpression("0x7fff_ffff"); + IntegerLiteralExpr negHex = parseExpression("0xffff_ffff"); + IntegerLiteralExpr posBin = parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111"); + IntegerLiteralExpr negBin = parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000"); + + assertThat(dec.asInt()).isEqualTo(2147483647); + assertThat(posOct.asInt()).isEqualTo(2147483647); // 0177_7777_7777 + assertThat(negOct.asInt()).isEqualTo(-1); // 0377_7777_7777 + assertThat(posHex.asInt()).isEqualTo(0x7fff_ffff); + assertThat(negHex.asInt()).isEqualTo(0xffff_ffff); + assertThat(posBin.asInt()).isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111); + assertThat(negBin.asInt()).isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000); + } + + @Test + public void lowerAndUpperBoundLongsAreConverted() { + LongLiteralExpr dec = parseExpression("9223372036854775807L"); + LongLiteralExpr posOct = parseExpression("07_7777_7777_7777_7777_7777L"); + LongLiteralExpr negOct = parseExpression("010_0000_0000_0000_0000_0000L"); + LongLiteralExpr posHex = parseExpression("0x7fff_ffff_ffff_ffffL"); + LongLiteralExpr negHex = parseExpression("0xffff_ffff_ffff_ffffL"); + LongLiteralExpr posBin = parseExpression("0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L"); + LongLiteralExpr negBin = parseExpression("0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L"); + + assertThat(dec.asLong()).isEqualTo(9223372036854775807L); + assertThat(posOct.asLong()).isEqualTo(9223372036854775807L); // 07_7777_7777_7777_7777_7777L + assertThat(negOct.asLong()).isEqualTo(-9223372036854775808L); // 010_0000_0000_0000_0000_0000L + assertThat(posHex.asLong()).isEqualTo(0x7fff_ffff_ffff_ffffL); + assertThat(negHex.asLong()).isEqualTo(0xffff_ffff_ffff_ffffL); + assertThat(posBin.asLong()).isEqualTo(0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111L); + assertThat(negBin.asLong()).isEqualTo(0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000L); + } + + @Test + public void charLiteralsAreConverted() { + CharLiteralExpr a = parseExpression("'a'"); + CharLiteralExpr percent = parseExpression("'%'"); + CharLiteralExpr tab = parseExpression("'\\t'"); + CharLiteralExpr newLine = parseExpression("'\\n'"); + CharLiteralExpr slash = parseExpression("'\\\\'"); + CharLiteralExpr quote = parseExpression("'\\''"); + CharLiteralExpr omega = parseExpression("'\\u03a9'"); + CharLiteralExpr unicode = parseExpression("'\\uFFFF'"); + CharLiteralExpr ascii = parseExpression("'\\177'"); + CharLiteralExpr trademark = parseExpression("'™'"); + + assertThat(a.asChar()).isEqualTo('a'); + assertThat(percent.asChar()).isEqualTo('%'); + assertThat(tab.asChar()).isEqualTo('\t'); + assertThat(newLine.asChar()).isEqualTo('\n'); + assertThat(slash.asChar()).isEqualTo('\\'); + assertThat(quote.asChar()).isEqualTo('\''); + assertThat(omega.asChar()).isEqualTo('\u03a9'); + assertThat(unicode.asChar()).isEqualTo('\uFFFF'); + assertThat(ascii.asChar()).isEqualTo('\177'); + assertThat(trademark.asChar()).isEqualTo('™'); + } + + @Test + public void lowerAndUpperBoundDoublesAreConverted() { + DoubleLiteralExpr posFloat = parseExpression("3.4028235e38f"); + DoubleLiteralExpr negFloat = parseExpression("1.40e-45f"); + DoubleLiteralExpr posDouble = parseExpression("1.7976931348623157e308"); + DoubleLiteralExpr negDouble = parseExpression("4.9e-324"); + DoubleLiteralExpr posHexFloat = parseExpression("0x1.fffffffffffffp1023"); + DoubleLiteralExpr negHexFloat = parseExpression("0x0.0000000000001P-1022"); + + assertThat(posFloat.asDouble()).isCloseTo(3.4028235e38f, Percentage.withPercentage(1)); + assertThat(negFloat.asDouble()).isCloseTo(1.40e-45f, Percentage.withPercentage(1)); + assertThat(posDouble.asDouble()).isEqualTo(1.7976931348623157e308); + assertThat(negDouble.asDouble()).isEqualTo(4.9e-324); + assertThat(posHexFloat.asDouble()).isEqualTo(0x1.fffffffffffffp1023); + assertThat(negHexFloat.asDouble()).isEqualTo(0x0.0000000000001P-1022); + } + + @Test + public void specialCharactersInStringsAreEscaped() { + assertThat(new StringLiteralExpr("\n").getValue()).isEqualTo("\\n"); + assertThat(new StringLiteralExpr("\r").getValue()).isEqualTo("\\r"); + assertThat(new StringLiteralExpr("").setEscapedValue("\n").getValue()).isEqualTo("\\n"); + assertThat(new StringLiteralExpr("").setEscapedValue("\r").getValue()).isEqualTo("\\r"); + assertThat(new StringLiteralExpr("").setEscapedValue("\n").asString()).isEqualTo("\n"); + assertThat(new StringLiteralExpr("").setEscapedValue("\r").asString()).isEqualTo("\r"); + assertThat(new StringLiteralExpr("Hello\nWorld\rHello\"World\'").asString()).isEqualTo("Hello\nWorld\rHello\"World\'"); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java new file mode 100644 index 000000000..258576420 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodCallExprTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static java.util.Optional.empty; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MethodCallExprTest { + + @Test + public void replaceLambdaIssue1290() { + MethodCallExpr methodCallExpr = parseExpression("callSomeFun(r -> r instanceof SomeType)").asMethodCallExpr(); + LambdaExpr lambdaExpr = methodCallExpr.getArgument(0).asLambdaExpr(); + MethodCallExpr lambdaWrapper = new MethodCallExpr("lambdaWrapper"); + lambdaExpr.replace(lambdaWrapper); + + assertEquals(2, methodCallExpr.getChildNodes().size()); + assertEquals(empty(), lambdaExpr.getParentNode()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java new file mode 100644 index 000000000..6f0643ba4 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/MethodReferenceExprTest.java @@ -0,0 +1,114 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.utils.TestUtils.assertExpressionValid; +import static org.junit.Assert.assertTrue; + +public class MethodReferenceExprTest { + + @Test + public void methodReferenceExprHasAlwaysAScope() { + assertTrue(new MethodReferenceExpr().getScope() != null); + } + + @Test + public void reference1() { + assertExpressionValid("String::length"); + } + + @Test + public void reference2() { + assertExpressionValid("System::currentTimeMillis // static method"); + } + + @Test + public void reference3() { + assertExpressionValid("List<String>::size // explicit type arguments for generic type"); + } + + @Test + public void reference4() { + assertExpressionValid("List::size // inferred type arguments for generic type"); + } + + @Test + public void reference5() { + assertExpressionValid("int[]::clone"); + } + + @Test + public void reference6() { + assertExpressionValid("T::tvarMember"); + } + + @Test + public void reference7() { + assertExpressionValid("System.out::println"); + } + + @Test + public void reference8() { + assertExpressionValid("\"abc\"::length"); + } + + @Test + public void reference9() { + assertExpressionValid("foo[x]::bar"); + } + + @Test + public void reference10() { + assertExpressionValid("(test ? list.replaceAll(String::trim) : list) :: iterator"); + } + + @Test + public void reference10Annotated1() { + assertExpressionValid("(test ? list.replaceAll(@A String::trim) : list) :: iterator"); + } + + @Test + public void reference11() { + assertExpressionValid("String::valueOf // overload resolution needed"); + } + + @Test + public void reference12() { + assertExpressionValid("Arrays::sort // type arguments inferred from context"); + } + + @Test + public void reference13() { + assertExpressionValid("Arrays::<String>sort // explicit type arguments"); + } + + @Test + public void reference14() { + assertExpressionValid("ArrayList<String>::new // constructor for parameterized type"); + } + + @Test + public void reference15() { + assertExpressionValid("ArrayList::new // inferred type arguments"); + } + + @Test + public void reference16() { + assertExpressionValid("Foo::<Integer>new // explicit type arguments"); + } + + @Test + public void reference17() { + assertExpressionValid("Bar<String>::<Integer>new // generic class, generic constructor"); + } + + @Test + public void reference18() { + assertExpressionValid("Outer.Inner::new // inner class constructor"); + } + + @Test + public void reference19() { + assertExpressionValid("int[]::new // array creation"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java new file mode 100644 index 000000000..6df3a6833 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/NameTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.expr; + +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.Assert.assertEquals; + +public class NameTest { + @Test + public void outerNameExprIsTheRightMostIdentifier() { + Name name = parseName("a.b.c"); + assertEquals("c", name.getIdentifier()); + } + + @Test + public void parsingAndUnparsingWorks() { + Name name = parseName("a.b.c"); + assertEquals("a.b.c", name.asString()); + } + + @Test(expected = ParseProblemException.class) + public void parsingEmptyNameThrowsException() { + parseName(""); + } + + @Test + public void nameCanHaveAnnotationsInside() { + Name name = parseName("a.@A b. @C c"); + assertEquals("a.b.c", name.asString()); + assertThat(name.getAnnotations()).containsExactly(new MarkerAnnotationExpr("C")); + assertThat(name.getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("A")); + + assertEquals("a.@A b.@C c", name.toString()); + assertEquals("a.@A b.@C c", ConcreteSyntaxModel.genericPrettyPrint(name)); + } + + @Test + public void importName() { + ImportDeclaration importDeclaration = parseImport("import java.@Abc util.List;"); + + assertThat(importDeclaration.getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc")); + + assertEquals("import java.@Abc util.List;" + EOL, importDeclaration.toString()); + assertEquals("import java.@Abc util.List;" + EOL, ConcreteSyntaxModel.genericPrettyPrint(importDeclaration)); + } + + @Test + public void packageName() { + CompilationUnit cu = parse("package @Abc p1.p2;"); + + assertThat(cu.getPackageDeclaration().get().getName().getQualifier().get().getAnnotations()).containsExactly(new MarkerAnnotationExpr("Abc")); + + assertEquals("package @Abc p1.p2;" + EOL + EOL, cu.toString()); + assertEquals("package @Abc p1.p2;" + EOL + EOL, ConcreteSyntaxModel.genericPrettyPrint(cu)); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java new file mode 100644 index 000000000..f7e028563 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/SimpleNameTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseSimpleName; +import static junit.framework.TestCase.assertEquals; + +public class SimpleNameTest { + + @Test + public void defaultConstructorSetsIdentifierToEmpty() { + assertEquals("empty", new SimpleName().getIdentifier()); + } + + @Test(expected = AssertionError.class) + public void identifierMustNotBeEmpty() { + new SimpleName(""); + } + + @Test(expected = AssertionError.class) + public void identifierMustNotBeNull() { + new SimpleName(null); + } + + @Test + public void unicodeEscapesArePreservedInIdentifiers() { + SimpleName name = parseSimpleName("xxx\\u2122xxx"); + assertEquals("xxx\\u2122xxx", name.asString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java new file mode 100644 index 000000000..50a9bfcfa --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/expr/StringLiteralExprTest.java @@ -0,0 +1,14 @@ +package com.github.javaparser.ast.expr; + +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static org.junit.Assert.*; + +public class StringLiteralExprTest { + @Test + public void unicodeEscapesArePreservedInStrings() { + StringLiteralExpr omega = parseExpression("\"xxx\\u03a9xxx\""); + assertEquals("xxx\\u03a9xxx", omega.getValue()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java new file mode 100644 index 000000000..ca821fbe9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/imports/ImportDeclarationTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.imports; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.ImportDeclaration; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ImportDeclarationTest { + @Test + public void singleTypeImportDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import a.b.c.X;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + + @Test + public void typeImportOnDemandDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import a.b.c.D.*;"); + assertEquals("a.b.c.D", i.getName().toString()); + assertEquals("D", i.getName().getIdentifier()); + } + + @Test + public void singleStaticImportDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.def;"); + assertEquals("a.b.c.X", i.getName().getQualifier().get().asString()); + assertEquals("def", i.getName().getIdentifier()); + } + + @Test + public void staticImportOnDemandDeclaration() { + ImportDeclaration i = JavaParser.parseImport("import static a.b.c.X.*;"); + assertEquals("a.b.c.X", i.getNameAsString()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java new file mode 100644 index 000000000..37728e76b --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithJavadocTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import org.junit.Test; + +import java.util.EnumSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeWithJavadocTest { + + @Test + public void removeJavaDocNegativeCaseNoComment() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + assertEquals(false, decl.removeJavaDocComment()); + } + + @Test + public void removeJavaDocNegativeCaseCommentNotJavaDoc() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new LineComment("A comment")); + assertEquals(false, decl.removeJavaDocComment()); + assertTrue(decl.getComment().isPresent()); + } + + @Test + public void removeJavaDocPositiveCase() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.setComment(new JavadocComment("A comment")); + assertEquals(true, decl.removeJavaDocComment()); + assertFalse(decl.getComment().isPresent()); + } + + @Test + public void getJavadocOnMethodWithLineCommentShouldReturnEmptyOptional() { + MethodDeclaration method = new MethodDeclaration(); + method.setLineComment("Lorem Ipsum."); + + assertFalse(method.getJavadocComment().isPresent()); + assertFalse(method.getJavadoc().isPresent()); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java new file mode 100644 index 000000000..20c302dd0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithModifiersTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.observer.AstObserverAdapter; +import com.github.javaparser.ast.observer.ObservableProperty; +import org.junit.Test; + +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.*; + +public class NodeWithModifiersTest { + + @Test + public void addModifierWorks() { + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.addModifier(Modifier.PUBLIC); + assertEquals(EnumSet.of(Modifier.PUBLIC), decl.getModifiers()); + } + + @Test + public void addModifierTriggerNotification() { + List<String> changes = new LinkedList<>(); + ClassOrInterfaceDeclaration decl = new ClassOrInterfaceDeclaration(EnumSet.noneOf(Modifier.class), + false, "Foo"); + decl.register(new AstObserverAdapter() { + @Override + public void propertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add("property " + property.name() + " is changed to " + newValue); + } + }); + decl.addModifier(Modifier.PUBLIC); + assertEquals(1, changes.size()); + assertEquals("property MODIFIERS is changed to [PUBLIC]", changes.get(0)); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java new file mode 100644 index 000000000..ad7e8bd7e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithOptionalScopeTest.java @@ -0,0 +1,28 @@ +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.expr.*; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class NodeWithOptionalScopeTest { + + @Test + public void commonExpressionWhichHaveInterfaceNodeWithOptionalScope() { + NodeWithOptionalScope methodCallExpr = new MethodCallExpr(new NameExpr("A"), "call"); + NodeWithOptionalScope objectCreationExpr = new ObjectCreationExpr(); + + assertTrue(methodCallExpr.getScope().isPresent()); + assertFalse(objectCreationExpr.getScope().isPresent()); + } + + @Test + public void removeScope() { + MethodCallExpr methodCallExpr = new MethodCallExpr(new NameExpr("A"), "method"); + + methodCallExpr.removeScope(); + + assertFalse(methodCallExpr.getScope().isPresent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java new file mode 100644 index 000000000..59aaf4e63 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithTraversableScopeTest.java @@ -0,0 +1,23 @@ +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.Assert.assertFalse; + +public class NodeWithTraversableScopeTest { + @Test + public void traverse1() { + NodeWithTraversableScope expression = parseExpression("getAddress().name.startsWith(\"abc\")"); + + assertInstanceOf(MethodCallExpr.class, expression); + expression = (NodeWithTraversableScope) expression.traverseScope().get(); + assertInstanceOf(FieldAccessExpr.class, expression); + expression = (NodeWithTraversableScope) expression.traverseScope().get(); + assertInstanceOf(MethodCallExpr.class, expression); + assertFalse(expression.traverseScope().isPresent()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java new file mode 100644 index 000000000..b736333c1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/nodeTypes/NodeWithVariablesTest.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.nodeTypes; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static org.junit.Assert.assertEquals; + +public class NodeWithVariablesTest { + + @Test + public void getCommonTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getCommonType()); + } + + @Test + public void getCommonTypeWorksForArrayTypes() { + parseVariableDeclarationExpr("int a[],b[]").getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnArrayDifferences() { + parseVariableDeclarationExpr("int a[],b[][]").getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnDodgySetterUsage() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getCommonType(); + } + + @Test(expected = AssertionError.class) + public void getCommonTypeFailsOnInvalidEmptyVariableList() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getCommonType(); + } + + @Test + public void getElementTypeWorksForNormalVariables() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + public void getElementTypeWorksForArrayTypes() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a[],b[]"); + assertEquals(PrimitiveType.intType(), declaration.getElementType()); + } + + @Test + public void getElementTypeIsOkayWithArrayDifferences() { + parseVariableDeclarationExpr("int a[],b[][]").getElementType(); + } + + @Test(expected = AssertionError.class) + public void getElementTypeFailsOnDodgySetterUsage() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a,b"); + declaration.getVariable(1).setType(String.class); + declaration.getElementType(); + } + + @Test(expected = AssertionError.class) + public void getElementTypeFailsOnInvalidEmptyVariableList() { + VariableDeclarationExpr declaration = parseVariableDeclarationExpr("int a"); + declaration.getVariables().clear(); + declaration.getElementType(); + } + +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java new file mode 100644 index 000000000..b590f32ab --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/observer/PropagatingAstObserverTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.observer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.FieldDeclaration; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class PropagatingAstObserverTest { + @Test + public void verifyPropagation() { + String code = "class A { }"; + CompilationUnit cu = JavaParser.parse(code); + List<String> changes = new ArrayList<>(); + AstObserver observer = new PropagatingAstObserver() { + @Override + public void concretePropertyChange(Node observedNode, ObservableProperty property, Object oldValue, Object newValue) { + changes.add(String.format("%s.%s changed from %s to %s", observedNode.getClass().getSimpleName(), property.name().toLowerCase(), oldValue, newValue)); + } + }; + cu.registerForSubtree(observer); + + assertEquals(Arrays.asList(), changes); + + FieldDeclaration fieldDeclaration = cu.getClassByName("A").get().addField("String", "foo"); + assertEquals(Arrays.asList(), changes); + assertEquals(true, fieldDeclaration.isRegistered(observer)); + + cu.getClassByName("A").get().getFieldByName("foo").get().getVariables().get(0).setName("Bar"); + assertEquals(Arrays.asList("VariableDeclarator.name changed from foo to Bar"), changes); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java new file mode 100644 index 000000000..5e5976ab8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/BlockStmtTest.java @@ -0,0 +1,21 @@ +package com.github.javaparser.ast.stmt; + +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import org.junit.Test; + +public class BlockStmtTest { + @Test + public void issue748AddingIdenticalStatementsDoesParentingRight() { + BlockStmt blockStmt = new BlockStmt(); + Expression exp = new NameExpr("x"); + MethodCallExpr expression = new MethodCallExpr(exp, "y"); + + blockStmt.addStatement(expression); + blockStmt.addStatement(expression.clone()); + // This fails when the issue exists: + String s = blockStmt.toString(); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java new file mode 100644 index 000000000..5775bd049 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/IfElseStmtTest.java @@ -0,0 +1,37 @@ +package com.github.javaparser.ast.stmt; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.NameExpr; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class IfElseStmtTest { + + @Test + public void issue1247withElseSingleStmt() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else doSomethingElse();"); + assertEquals(false, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(false, ifStmt.hasCascadingIfStmt()); + } + + @Test + public void issue1247withElseBlockStmt() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond) doSomething(); else { doSomethingElse(); }"); + assertEquals(true, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(false, ifStmt.hasCascadingIfStmt()); + } + + @Test + public void issue1247withElseSingleStmtWhichIsAnIf() { + IfStmt ifStmt = (IfStmt) JavaParser.parseStatement("if (cond1) doSomething(); else if (cond2) doSomethingElse();"); + assertEquals(false, ifStmt.hasElseBlock()); + assertEquals(true, ifStmt.hasElseBranch()); + assertEquals(true, ifStmt.hasCascadingIfStmt()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java new file mode 100644 index 000000000..1a63b21f7 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/stmt/TryStmtTest.java @@ -0,0 +1,81 @@ +package com.github.javaparser.ast.stmt; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.validator.Java9Validator; +import org.junit.Test; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertInstanceOf; +import static org.junit.Assert.assertTrue; + +public class TryStmtTest { + @Test + public void simpleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + } + + @Test + public void multipleTest() { + TryStmt tryStmt = parse9("try(Reader x = new FileReader(); Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void modifiersTest() { + TryStmt tryStmt = parse9("try(final @A Reader x = new FileReader()){}"); + assertInstanceOf(VariableDeclarationExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void simpleVariable() { + TryStmt tryStmt = parse9("try(a){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void twoSimpleVariables() { + TryStmt tryStmt = parse9("try(a;b){}"); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(0)); + assertInstanceOf(NameExpr.class, tryStmt.getResources().get(1)); + + } + + @Test + public void complexVariable() { + TryStmt tryStmt = parse9("try(a.b.c){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void superAccess() { + TryStmt tryStmt = parse9("try(super.a){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + + } + + @Test + public void outerClassAccess() { + TryStmt tryStmt = parse9("try(X.this.a){}"); + assertInstanceOf(FieldAccessExpr.class, tryStmt.getResources().get(0)); + + } + + private <T> T parse9(String code) { + JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult<Statement> result = parser.parse(ParseStart.STATEMENT, provider(code)); + assertTrue(result.toString(), result.isSuccessful()); + return (T) result.getResult().get(); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java new file mode 100644 index 000000000..3fdee8e43 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/ArrayTypeTest.java @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.type; + +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +public class ArrayTypeTest { + @Test + public void getFieldDeclarationWithArrays() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("@C int @A[] @B[] a @X[] @Y[];").asFieldDeclaration(); + + ArrayType arrayType1 = fieldDeclaration.getVariable(0).getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + ArrayType arrayType3 = arrayType2.getComponentType().asArrayType(); + ArrayType arrayType4 = arrayType3.getComponentType().asArrayType(); + PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType(); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(fieldDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(fieldDeclaration); + } + + @Test + public void getVariableDeclarationWithArrays() { + ExpressionStmt variableDeclarationStatement = parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = variableDeclarationStatement.getExpression().asVariableDeclarationExpr(); + + ArrayType arrayType1 = variableDeclarationExpr.getVariable(0).getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + ArrayType arrayType3 = arrayType2.getComponentType().asArrayType(); + ArrayType arrayType4 = arrayType3.getComponentType().asArrayType(); + PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType(); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y"))); + + assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT); + assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr); + } + + @Test + public void getMethodDeclarationWithArrays() { + MethodDeclaration methodDeclaration = parseBodyDeclaration("@C int @A[] a() @B[] {}").asMethodDeclaration(); + + ArrayType arrayType1 = methodDeclaration.getType().asArrayType(); + ArrayType arrayType2 = arrayType1.getComponentType().asArrayType(); + Type elementType = arrayType2.getComponentType(); + assertThat(elementType).isInstanceOf(PrimitiveType.class); + + assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(methodDeclaration.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(methodDeclaration.getType().getParentNode().get()).isSameAs(methodDeclaration); + } + + @Test + public void getParameterWithArrays() { + MethodDeclaration methodDeclaration = parseBodyDeclaration("void a(@C int @A[] a @B[]) {}").asMethodDeclaration(); + + Parameter parameter = methodDeclaration.getParameter(0); + + ArrayType outerArrayType = parameter.getType().asArrayType(); + + ArrayType innerArrayType = outerArrayType.getComponentType().asArrayType(); + PrimitiveType elementType = innerArrayType.getComponentType().asPrimitiveType(); + + assertThat(elementType).isInstanceOf(PrimitiveType.class); + assertThat(outerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A"))); + assertThat(innerArrayType.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B"))); + assertThat(parameter.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C"))); + + assertThat(parameter.getType().getParentNode().get()).isSameAs(parameter); + } + + @Test + public void setVariableDeclarationWithArrays() { + ExpressionStmt variableDeclarationStatement = parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = variableDeclarationStatement.getExpression().asVariableDeclarationExpr(); + + variableDeclarationExpr.getVariable(0).setType(new ArrayType(new ArrayType(PrimitiveType.intType()))); + assertEquals("@C int[][] a;", variableDeclarationStatement.toString()); + } + + @Test + public void setFieldDeclarationWithArrays() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[][] a[][];").asFieldDeclaration(); + fieldDeclaration.getVariable(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a;", fieldDeclaration.toString()); + } + + @Test + public void setMethodDeclarationWithArrays() { + MethodDeclaration method = parseBodyDeclaration("int[][] a()[][] {}").asMethodDeclaration(); + method.setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("Blob[][] a() {" + EOL + "}", method.toString()); + } + + @Test + public void fieldDeclarationWithArraysHasCorrectOrigins() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int[] a[];").asFieldDeclaration(); + + Type outerType = fieldDeclaration.getVariables().get(0).getType(); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + public void methodDeclarationWithArraysHasCorrectOrigins() { + MethodDeclaration method = (MethodDeclaration) parseBodyDeclaration("int[] a()[] {}"); + + Type outerType = method.getType(); + assertEquals(ArrayType.Origin.TYPE, outerType.asArrayType().getOrigin()); + assertEquals(ArrayType.Origin.NAME, outerType.asArrayType().getComponentType().asArrayType().getOrigin()); + } + + @Test + public void setParameterWithArrays() { + MethodDeclaration method = parseBodyDeclaration("void a(int[][] a[][]) {}").asMethodDeclaration(); + method.getParameter(0).setType(new ArrayType(new ArrayType(parseClassOrInterfaceType("Blob")))); + + assertEquals("void a(Blob[][] a) {" + EOL + "}", method.toString()); + } + + @Test + public void getArrayCreationType() { + ArrayCreationExpr expr = parseExpression("new int[]"); + ArrayType outerType = expr.createdType().asArrayType(); + Type innerType = outerType.getComponentType(); + assertThat(innerType).isEqualTo(expr.getElementType()); + } + + @Test + public void ellipsisCanHaveAnnotationsToo() { + Parameter p = parseParameter("int[]@X...a[]"); + + assertThat(p.getVarArgsAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X"))); + assertEquals("int[][]@X ... a", p.toString()); + assertEquals("int[][]@X... a", ConcreteSyntaxModel.genericPrettyPrint(p)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java new file mode 100644 index 000000000..17244f383 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/type/TypeTest.java @@ -0,0 +1,68 @@ +package com.github.javaparser.ast.type; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.validator.Java5Validator; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseType; +import static com.github.javaparser.JavaParser.parseVariableDeclarationExpr; +import static com.github.javaparser.ParseStart.VARIABLE_DECLARATION_EXPR; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static org.junit.Assert.*; + +public class TypeTest { + @Test + public void asString() { + assertEquals("int", typeAsString("int x")); + assertEquals("List<Long>", typeAsString("List<Long> x")); + assertEquals("String", typeAsString("@A String x")); + assertEquals("List<? extends Object>", typeAsString("List<? extends Object> x")); + } + + @Test(expected = ParseProblemException.class) + public void primitiveTypeArgumentDefaultValidator() { + typeAsString("List<long> x;"); + } + + @Test + public void primitiveTypeArgumentLenientValidator() { + ParserConfiguration config = new ParserConfiguration() + .setLanguageLevel(RAW); + config.getPostProcessors().add(new Java5Validator() {{ + remove(noPrimitiveGenericArguments); + }}.postProcessor()); + + ParseResult<VariableDeclarationExpr> result = new JavaParser(config).parse( + VARIABLE_DECLARATION_EXPR, provider("List<long> x")); + assertTrue(result.isSuccessful()); + + VariableDeclarationExpr decl = result.getResult().get(); + assertEquals("List<long>", decl.getVariable(0).getType().asString()); + } + + private String typeAsString(String s) { + return parseVariableDeclarationExpr(s).getVariable(0).getType().asString(); + } + + @Test + public void arrayType() { + Type type = parseType("int[]"); + assertTrue(type.isArrayType()); + ArrayType arrayType = type.asArrayType(); + final ArrayType[] s = new ArrayType[1]; + type.ifArrayType(t -> s[0] = t); + assertNotNull(s[0]); + } + + @Test + public void issue1251() { + final Type type = parseType("TypeUtilsTest<String>.Tester"); + assertEquals("TypeUtilsTest<String>.Tester", type.toString()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java new file mode 100644 index 000000000..8c2b93568 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java10ValidatorTest.java @@ -0,0 +1,108 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Ignore; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.CLASS_BODY; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java10ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + + @Test + public void varAllowedInLocalVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a = 5;")); + assertNoProblems(result); + } + + @Test + public void varAllowedInForEach() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a : as){}")); + assertNoProblems(result); + } + + @Test + public void varAllowedInOldFor() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(var a = 5;a<9;a++){}")); + assertNoProblems(result); + } + + @Test + public void varNotAllowedInCast() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int a = (var)20;")); + assertNoProblems(result); + } + + @Test + public void varNotAllowedInTryWithResources() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(var f = new FileReader(\"\")){ }catch (Exception e){ }")); + assertProblems(result, "(line 1,col 5) \"var\" is not allowed here."); + } + + @Test + public void varNotAllowedInField() { + ParseResult<BodyDeclaration<?>> result = javaParser.parse(CLASS_BODY, provider("var a = 20;")); + assertProblems(result, "(line 1,col 1) \"var\" is not allowed here."); + } + + @Test + public void varNotAllowedInTypeArguments() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("new X<var>();")); + assertProblems(result, "(line 1,col 7) \"var\" is not allowed here."); + } + + @Test + public void varNotAllowedInLambdaParameters() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x) -> null);")); + assertProblems(result, "(line 1,col 4) \"var\" is not allowed here."); + } + + @Test + public void emptyInitializerNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a;")); + assertProblems(result, "(line 1,col 1) \"var\" needs an initializer."); + } + + @Test + public void multipleVariablesNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=1, b=2;")); + assertProblems(result, "(line 1,col 1) \"var\" only takes a single variable."); + } + + @Test + public void nullVariablesNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=null;")); + assertProblems(result, "(line 1,col 1) \"var\" cannot infer type from just null."); + } + + @Test + public void arrayDimensionBracketsNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new String[]{};")); + assertProblems(result, "(line 1,col 1) \"var\" cannot infer array types."); + } + + // This is pretty hard to impossible to implement correctly with just the AST. + @Ignore + @Test + public void selfReferenceNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=a;")); + assertProblems(result, ""); + } + + // Can be implemented once https://github.com/javaparser/javaparser/issues/1434 is implemented. + @Ignore + @Test + public void polyExpressionAsInitializerNotAllowed() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var a=new ArrayList<>();")); + assertProblems(result, ""); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java new file mode 100644 index 000000000..1e1f8c0f8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java11ValidatorTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_11_PREVIEW; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; + +public class Java11ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_11_PREVIEW)); + + @Test + public void varAllowedInLocalVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("x((var x, var y) -> x+y);")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java new file mode 100644 index 000000000..7160bcfb9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_0ValidatorTest.java @@ -0,0 +1,98 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; +import static org.junit.Assert.assertEquals; + +public class Java1_0ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_0)); + + @Test + public void tryWithoutResources() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(X x=new Y()){}")); + assertProblems(result, + "(line 1,col 1) Catch with resource is not supported.", + "(line 1,col 1) Try has no finally and no catch."); + } + + @Test + public void classExtendingMoreThanOne() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y, Z {}")); + assertProblems(result, "(line 1,col 20) A class cannot extend more than one other class."); + } + + @Test + public void interfaceUsingImplements() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X implements Y {}")); + assertProblems(result, "(line 1,col 24) An interface cannot implement other interfaces."); + } + + @Test + public void interfaceWithInitializer() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {{}}")); + assertProblems(result, "(line 1,col 14) An interface cannot have initializers."); + } + + @Test + public void defaultInClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X {default void a(){};}")); + assertProblems(result, "(line 1,col 10) 'default' is not allowed here."); + } + + @Test + public void leftHandAssignmentCannotBeAConditional() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(1==2)=3")); + assertProblems(result, "(line 1,col 1) Illegal left hand side of an assignment."); + } + + @Test + public void leftHandAssignmentCannotBeEmptyBraces() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("()=3")); + assertProblems(result, + "(line 1,col 1) Illegal left hand side of an assignment.", + "(line 1,col 1) Lambdas are not supported."); + } + + @Test + public void leftHandAssignmentCanBeInBraces() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("(i) += (i) += 1")); + assertNoProblems(result); + } + + @Test + public void noInnerClasses() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}")); + assertProblems(result, "(line 1,col 9) inner classes or interfaces are not supported."); + } + + @Test + public void noReflection() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class")); + assertProblems(result, "(line 1,col 1) Reflection is not supported."); + } + + @Test + public void nonEmptyList() { + ArrayCreationExpr expr = new ArrayCreationExpr(PrimitiveType.booleanType()); + List<Problem> problems= new ArrayList<>(); + new Java1_0Validator().accept(expr, new ProblemReporter(problems::add)); + assertEquals("ArrayCreationExpr.levels can not be empty.", problems.get(0).getMessage()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java new file mode 100644 index 000000000..6331d9ab1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_1ValidatorTest.java @@ -0,0 +1,292 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_1ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_1)); + + public static final String allModifiers = "public protected private abstract static final transient volatile synchronized native strictfp transitive default "; + + @Test + public void topClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'strictfp' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here." + ); + } + + @Test + public void nestedClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void localClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}")); + assertProblems(result, + "(line 1,col 20) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 20) Can have only one of 'final', 'abstract'.", + "(line 1,col 20) 'transient' is not allowed here.", + "(line 1,col 20) 'volatile' is not allowed here.", + "(line 1,col 20) 'default' is not allowed here.", + "(line 1,col 20) 'synchronized' is not allowed here.", + "(line 1,col 20) 'native' is not allowed here.", + "(line 1,col 20) 'transitive' is not allowed here.", + "(line 1,col 20) 'strictfp' is not allowed here.", + "(line 1,col 20) 'static' is not allowed here.", + "(line 1,col 20) 'public' is not allowed here.", + "(line 1,col 20) 'private' is not allowed here.", + "(line 1,col 20) 'protected' is not allowed here." + ); + } + + @Test + public void topInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'strictfp' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + public void nestedInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void constructor() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'static' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void constructorParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 11) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 11) Can have only one of 'final', 'abstract'.", + "(line 1,col 11) 'transient' is not allowed here.", + "(line 1,col 11) 'volatile' is not allowed here.", + "(line 1,col 11) 'synchronized' is not allowed here.", + "(line 1,col 11) 'native' is not allowed here.", + "(line 1,col 11) 'strictfp' is not allowed here.", + "(line 1,col 11) 'default' is not allowed here.", + "(line 1,col 11) 'abstract' is not allowed here.", + "(line 1,col 11) 'static' is not allowed here.", + "(line 1,col 11) 'transitive' is not allowed here.", + "(line 1,col 11) 'private' is not allowed here.", + "(line 1,col 11) 'public' is not allowed here.", + "(line 1,col 11) 'protected' is not allowed here." + ); + } + + @Test + public void classMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void interfaceMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'strictfp' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'default' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here.", + "(line 1,col 13) 'static' is not allowed here." + ); + } + + @Test + public void methodParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 15) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 15) Can have only one of 'final', 'abstract'.", + "(line 1,col 15) 'transient' is not allowed here.", + "(line 1,col 15) 'volatile' is not allowed here.", + "(line 1,col 15) 'synchronized' is not allowed here.", + "(line 1,col 15) 'native' is not allowed here.", + "(line 1,col 15) 'strictfp' is not allowed here.", + "(line 1,col 15) 'abstract' is not allowed here.", + "(line 1,col 15) 'default' is not allowed here.", + "(line 1,col 15) 'static' is not allowed here.", + "(line 1,col 15) 'transitive' is not allowed here.", + "(line 1,col 15) 'private' is not allowed here.", + "(line 1,col 15) 'public' is not allowed here.", + "(line 1,col 15) 'protected' is not allowed here." + ); + } + + @Test + public void field() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void localVariable() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}")); + assertProblems(result, + "(line 1,col 17) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 17) Can have only one of 'final', 'abstract'.", + "(line 1,col 17) 'transient' is not allowed here.", + "(line 1,col 17) 'volatile' is not allowed here.", + "(line 1,col 17) 'synchronized' is not allowed here.", + "(line 1,col 17) 'native' is not allowed here.", + "(line 1,col 17) 'default' is not allowed here.", + "(line 1,col 17) 'strictfp' is not allowed here.", + "(line 1,col 17) 'abstract' is not allowed here.", + "(line 1,col 17) 'static' is not allowed here.", + "(line 1,col 17) 'transitive' is not allowed here.", + "(line 1,col 17) 'private' is not allowed here.", + "(line 1,col 17) 'public' is not allowed here.", + "(line 1,col 17) 'protected' is not allowed here." + ); + } + + + @Test + public void catchParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 144) Can have only one of 'final', 'abstract'.", + "(line 1,col 144) 'transient' is not allowed here.", + "(line 1,col 144) 'volatile' is not allowed here.", + "(line 1,col 144) 'synchronized' is not allowed here.", + "(line 1,col 144) 'native' is not allowed here.", + "(line 1,col 144) 'default' is not allowed here.", + "(line 1,col 144) 'strictfp' is not allowed here.", + "(line 1,col 144) 'abstract' is not allowed here.", + "(line 1,col 144) 'static' is not allowed here.", + "(line 1,col 144) 'transitive' is not allowed here.", + "(line 1,col 144) 'private' is not allowed here.", + "(line 1,col 144) 'public' is not allowed here.", + "(line 1,col 144) 'protected' is not allowed here." + ); + } + + @Test + public void innerClasses() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{class Y{}}")); + assertNoProblems(result); + } + + @Test + public void localInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "interface I{}}}")); + assertProblems(result, "(line 1,col 20) There is no such thing as a local interface." + ); + } + + @Test + public void reflection() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("Abc.class")); + assertNoProblems(result); + } + + @Test + public void strictfpAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java new file mode 100644 index 000000000..3ae7018fe --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_2ValidatorTest.java @@ -0,0 +1,275 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_2ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_2)); + + private final String allModifiers = "public protected private abstract static final transient volatile synchronized native strictfp transitive default "; + + @Test + public void topClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "class X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here." + ); + } + + @Test + public void nestedClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "class I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void localClass() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{ void x() {" + allModifiers + "class I{}}}")); + assertProblems(result, + "(line 1,col 20) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 20) Can have only one of 'final', 'abstract'.", + "(line 1,col 20) Can have only one of 'native', 'strictfp'.", + "(line 1,col 20) 'transient' is not allowed here.", + "(line 1,col 20) 'volatile' is not allowed here.", + "(line 1,col 20) 'default' is not allowed here.", + "(line 1,col 20) 'synchronized' is not allowed here.", + "(line 1,col 20) 'native' is not allowed here.", + "(line 1,col 20) 'transitive' is not allowed here.", + "(line 1,col 20) 'static' is not allowed here.", + "(line 1,col 20) 'public' is not allowed here.", + "(line 1,col 20) 'private' is not allowed here.", + "(line 1,col 20) 'protected' is not allowed here." + ); + } + + @Test + public void topInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + public void nestedInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void constructor() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "X(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'static' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void constructorParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{X(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 11) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 11) Can have only one of 'final', 'abstract'.", + "(line 1,col 11) Can have only one of 'native', 'strictfp'.", + "(line 1,col 11) 'transient' is not allowed here.", + "(line 1,col 11) 'volatile' is not allowed here.", + "(line 1,col 11) 'synchronized' is not allowed here.", + "(line 1,col 11) 'native' is not allowed here.", + "(line 1,col 11) 'strictfp' is not allowed here.", + "(line 1,col 11) 'default' is not allowed here.", + "(line 1,col 11) 'abstract' is not allowed here.", + "(line 1,col 11) 'static' is not allowed here.", + "(line 1,col 11) 'transitive' is not allowed here.", + "(line 1,col 11) 'private' is not allowed here.", + "(line 1,col 11) 'public' is not allowed here.", + "(line 1,col 11) 'protected' is not allowed here." + ); + } + + @Test + public void classMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void interfaceMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'default' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here.", + "(line 1,col 13) 'static' is not allowed here." + ); + } + + @Test + public void methodParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(" + allModifiers + " int i){};}")); + assertProblems(result, + "(line 1,col 15) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 15) Can have only one of 'final', 'abstract'.", + "(line 1,col 15) Can have only one of 'native', 'strictfp'.", + "(line 1,col 15) 'transient' is not allowed here.", + "(line 1,col 15) 'volatile' is not allowed here.", + "(line 1,col 15) 'synchronized' is not allowed here.", + "(line 1,col 15) 'native' is not allowed here.", + "(line 1,col 15) 'strictfp' is not allowed here.", + "(line 1,col 15) 'abstract' is not allowed here.", + "(line 1,col 15) 'default' is not allowed here.", + "(line 1,col 15) 'static' is not allowed here.", + "(line 1,col 15) 'transitive' is not allowed here.", + "(line 1,col 15) 'private' is not allowed here.", + "(line 1,col 15) 'public' is not allowed here.", + "(line 1,col 15) 'protected' is not allowed here." + ); + } + + @Test + public void field() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "int i;}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'strictfp' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void localVariable() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){" + allModifiers + "int i;}}")); + assertProblems(result, + "(line 1,col 17) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 17) Can have only one of 'final', 'abstract'.", + "(line 1,col 17) Can have only one of 'native', 'strictfp'.", + "(line 1,col 17) 'transient' is not allowed here.", + "(line 1,col 17) 'volatile' is not allowed here.", + "(line 1,col 17) 'synchronized' is not allowed here.", + "(line 1,col 17) 'native' is not allowed here.", + "(line 1,col 17) 'default' is not allowed here.", + "(line 1,col 17) 'strictfp' is not allowed here.", + "(line 1,col 17) 'abstract' is not allowed here.", + "(line 1,col 17) 'static' is not allowed here.", + "(line 1,col 17) 'transitive' is not allowed here.", + "(line 1,col 17) 'private' is not allowed here.", + "(line 1,col 17) 'public' is not allowed here.", + "(line 1,col 17) 'protected' is not allowed here." + ); + } + + @Test + public void catchParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ try{}catch(" + allModifiers + " Integer x){}}}")); + assertProblems(result, + "(line 1,col 144) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 144) Can have only one of 'final', 'abstract'.", + "(line 1,col 144) Can have only one of 'native', 'strictfp'.", + "(line 1,col 144) 'transient' is not allowed here.", + "(line 1,col 144) 'volatile' is not allowed here.", + "(line 1,col 144) 'synchronized' is not allowed here.", + "(line 1,col 144) 'native' is not allowed here.", + "(line 1,col 144) 'default' is not allowed here.", + "(line 1,col 144) 'strictfp' is not allowed here.", + "(line 1,col 144) 'abstract' is not allowed here.", + "(line 1,col 144) 'static' is not allowed here.", + "(line 1,col 144) 'transitive' is not allowed here.", + "(line 1,col 144) 'private' is not allowed here.", + "(line 1,col 144) 'public' is not allowed here.", + "(line 1,col 144) 'protected' is not allowed here." + ); + } + + @Test + public void strictfpNotAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int strictfp;")); + assertProblems(result, "(line 1,col 5) 'strictfp' cannot be used as an identifier as it is a keyword."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java new file mode 100644 index 000000000..b10114abf --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_3ValidatorTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_3ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_3)); + + @Test + public void noAssert() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;")); + assertProblems(result, "(line 1,col 1) 'assert' keyword is not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java new file mode 100644 index 000000000..ed0be99fe --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java1_4ValidatorTest.java @@ -0,0 +1,70 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java1_4ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_1_4)); + + @Test + public void yesAssert() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("assert a;")); + assertNoProblems(result); + } + + @Test + public void noGenerics() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b;}")); + assertProblems(result, + "(line 1,col 12) Generics are not supported.", + "(line 1,col 1) Generics are not supported." + ); + } + + @Test + public void noAnnotations() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("@Abc @Def() @Ghi(a=3) @interface X{}")); + assertProblems(result, + "(line 1,col 6) Annotations are not supported.", + "(line 1,col 13) Annotations are not supported.", + "(line 1,col 1) Annotations are not supported." + ); + } + + @Test + public void novarargs() { + ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x")); + assertProblems(result, "(line 1,col 1) Varargs are not supported."); + } + + @Test + public void noforeach() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}")); + assertProblems(result, "(line 1,col 1) For-each loops are not supported."); + } + + @Test + public void staticImport() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;")); + assertProblems(result, + "(line 1,col 17) Static imports are not supported.", + "(line 1,col 1) Static imports are not supported."); + } + + @Test + public void enumAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;")); + assertNoProblems(result); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java new file mode 100644 index 000000000..315167fda --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java5ValidatorTest.java @@ -0,0 +1,155 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.*; +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java5ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_5)); + + @Test + public void genericsWithoutDiamond() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}")); + assertProblems(result, "(line 1,col 33) The diamond operator is not supported."); + } + + @Test + public void topAnnotationDeclaration() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "@interface X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + public void nestedAnnotationDeclaration() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "@interface I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void annotationMember() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("@interface X{" + allModifiers + "int x();}")); + assertProblems(result, + "(line 1,col 14) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 14) Can have only one of 'final', 'abstract'.", + "(line 1,col 14) Can have only one of 'native', 'strictfp'.", + "(line 1,col 14) 'transient' is not allowed here.", + "(line 1,col 14) 'volatile' is not allowed here.", + "(line 1,col 14) 'final' is not allowed here.", + "(line 1,col 14) 'synchronized' is not allowed here.", + "(line 1,col 14) 'default' is not allowed here.", + "(line 1,col 14) 'native' is not allowed here.", + "(line 1,col 14) 'protected' is not allowed here.", + "(line 1,col 14) 'private' is not allowed here.", + "(line 1,col 14) 'strictfp' is not allowed here.", + "(line 1,col 14) 'static' is not allowed here.", + "(line 1,col 14) 'transitive' is not allowed here." + ); + } + + @Test + public void topEnum() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(allModifiers + "enum X{}")); + assertProblems(result, + "(line 1,col 1) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 1) Can have only one of 'final', 'abstract'.", + "(line 1,col 1) Can have only one of 'native', 'strictfp'.", + "(line 1,col 1) 'transient' is not allowed here.", + "(line 1,col 1) 'volatile' is not allowed here.", + "(line 1,col 1) 'synchronized' is not allowed here.", + "(line 1,col 1) 'default' is not allowed here.", + "(line 1,col 1) 'native' is not allowed here.", + "(line 1,col 1) 'transitive' is not allowed here.", + "(line 1,col 1) 'static' is not allowed here.", + "(line 1,col 1) 'abstract' is not allowed here.", + "(line 1,col 1) 'final' is not allowed here.", + "(line 1,col 1) 'private' is not allowed here.", + "(line 1,col 1) 'protected' is not allowed here." + ); + } + + @Test + public void nestedEnum() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{" + allModifiers + "enum I{}}")); + assertProblems(result, + "(line 1,col 9) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 9) Can have only one of 'final', 'abstract'.", + "(line 1,col 9) Can have only one of 'native', 'strictfp'.", + "(line 1,col 9) 'transient' is not allowed here.", + "(line 1,col 9) 'volatile' is not allowed here.", + "(line 1,col 9) 'default' is not allowed here.", + "(line 1,col 9) 'abstract' is not allowed here.", + "(line 1,col 9) 'final' is not allowed here.", + "(line 1,col 9) 'synchronized' is not allowed here.", + "(line 1,col 9) 'native' is not allowed here.", + "(line 1,col 9) 'transitive' is not allowed here." + ); + } + + @Test + public void varargs() { + ParseResult<Parameter> result = javaParser.parse(PARAMETER, provider("String... x")); + assertNoProblems(result); + } + + @Test + public void foreach() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(X x: xs){}")); + assertNoProblems(result); + } + + @Test + public void staticImport() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("import static x;import static x.*;import x.X;import x.*;")); + assertNoProblems(result); + } + + @Test + public void noPrimitiveTypeArguments() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X extends Y<int> {}")); + assertProblems(result, "(line 1,col 17) Type arguments may not be primitive."); + } + + @Test + public void enumAllowedAsIdentifier() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("int enum;")); + assertProblems(result, "(line 1,col 5) 'enum' cannot be used as an identifier as it is a keyword."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java new file mode 100644 index 000000000..d066abe07 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java6ValidatorTest.java @@ -0,0 +1,42 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java6ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_6)); + + @Test + public void noStringsInSwitch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}")); + assertProblems(result, "(line 1,col 16) Strings in switch statements are not supported."); + } + + @Test + public void nobinaryIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01")); + assertProblems(result, "(line 1,col 1) Binary literal values are not supported."); + } + + @Test + public void noUnderscoresInIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertProblems(result, "(line 1,col 1) Underscores in literal values are not supported."); + } + + @Test + public void noMultiCatch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); + assertProblems(result, "(line 1,col 12) Multi-catch is not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java new file mode 100644 index 000000000..a2a03f837 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java7ValidatorTest.java @@ -0,0 +1,107 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.UnionType; +import org.junit.Test; + +import java.util.*; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.EXPRESSION; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java7ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_7)); + + @Test + public void generics() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X<A>{List<String> b = new ArrayList<>();}")); + assertNoProblems(result); + } + + @Test + public void defaultMethodWithoutBody() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' is not allowed here."); + } + + @Test + public void tryWithoutAnything() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}")); + assertProblems(result, "(line 1,col 1) Try has no finally, no catch, and no resources."); + } + + @Test + public void tryWithResourceVariableDeclaration() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(Reader r = new Reader()){}")); + assertNoProblems(result); + } + + @Test + public void tryWithResourceReference() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertProblems(result, "(line 1,col 1) Try with resources only supports variable declarations."); + } + + @Test + public void stringsInSwitch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("switch(x){case \"abc\": ;}")); + assertNoProblems(result); + } + + @Test + public void binaryIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("0b01")); + assertNoProblems(result); + } + + @Test + public void underscoresInIntegerLiterals() { + ParseResult<Expression> result = javaParser.parse(EXPRESSION, provider("1_000_000")); + assertNoProblems(result); + } + + @Test + public void multiCatch() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try{}catch(Abc|Def e){}")); + assertNoProblems(result); + } + + @Test + public void multiCatchWithoutElements() { + UnionType unionType = new UnionType(); + + List<Problem> problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "UnionType.elements can not be empty."); + } + + @Test + public void multiCatchWithOneElement() { + UnionType unionType = new UnionType(); + unionType.getElements().add(new ClassOrInterfaceType()); + + List<Problem> problems = new ArrayList<>(); + new Java7Validator().accept(unionType, new ProblemReporter(problems::add)); + + assertProblems(problems, "Union type (multi catch) must have at least two elements."); + } + + @Test + public void noLambdas() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + assertProblems(result, "(line 1,col 3) Lambdas are not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java new file mode 100644 index 000000000..216fb5b13 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java8ValidatorTest.java @@ -0,0 +1,82 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java8ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_8)); + + @Test + public void localInterface() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X {void a(){interface I{}};}")); + assertProblems(result, "(line 1,col 19) There is no such thing as a local interface."); + } + + @Test + public void lambdaParameter() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("class X{int x(){ a((" + allModifiers + " Integer x) -> 10);}}")); + assertProblems(result, + "(line 1,col 21) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 21) Can have only one of 'final', 'abstract'.", + "(line 1,col 21) Can have only one of 'native', 'strictfp'.", + "(line 1,col 21) 'transient' is not allowed here.", + "(line 1,col 21) 'volatile' is not allowed here.", + "(line 1,col 21) 'synchronized' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'default' is not allowed here.", + "(line 1,col 21) 'native' is not allowed here.", + "(line 1,col 21) 'strictfp' is not allowed here.", + "(line 1,col 21) 'abstract' is not allowed here.", + "(line 1,col 21) 'static' is not allowed here.", + "(line 1,col 21) 'transitive' is not allowed here.", + "(line 1,col 21) 'private' is not allowed here.", + "(line 1,col 21) 'public' is not allowed here.", + "(line 1,col 21) 'protected' is not allowed here." + ); + } + + @Test + public void interfaceMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here.", + "(line 1,col 13) 'private' is not allowed here." + ); + } + + @Test + public void defaultMethodWithoutBody() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X {default void a();}")); + assertProblems(result, "(line 1,col 14) 'default' methods must have a body."); + } + + @Test + public void lambdas() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a(() -> 1);")); + assertNoProblems(result); + } + + @Test + public void noModules() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + assertProblems(result, "(line 1,col 1) Modules are not supported."); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java new file mode 100644 index 000000000..911f6a984 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/validator/Java9ValidatorTest.java @@ -0,0 +1,79 @@ +package com.github.javaparser.ast.validator; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.Test; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.ast.validator.Java1_1ValidatorTest.allModifiers; +import static com.github.javaparser.utils.TestUtils.assertNoProblems; +import static com.github.javaparser.utils.TestUtils.assertProblems; + +public class Java9ValidatorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + + @Test + public void underscoreIdentifiers() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("a.b._.c.d = act(_, _ -> _);")); + assertProblems(result, + "(line 1,col 5) '_' is a reserved keyword.", + "(line 1,col 17) '_' is a reserved keyword.", + "(line 1,col 20) '_' is a reserved keyword.", + "(line 1,col 25) '_' is a reserved keyword." + ); + } + + @Test + public void moduleRequires() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("module x{requires " + allModifiers + " a;}")); + assertProblems(result, + "(line 1,col 10) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 10) Can have only one of 'final', 'abstract'.", + "(line 1,col 10) Can have only one of 'native', 'strictfp'.", + "(line 1,col 10) 'transient' is not allowed here.", + "(line 1,col 10) 'volatile' is not allowed here.", + "(line 1,col 10) 'final' is not allowed here.", + "(line 1,col 10) 'synchronized' is not allowed here.", + "(line 1,col 10) 'default' is not allowed here.", + "(line 1,col 10) 'native' is not allowed here.", + "(line 1,col 10) 'private' is not allowed here.", + "(line 1,col 10) 'protected' is not allowed here.", + "(line 1,col 10) 'strictfp' is not allowed here.", + "(line 1,col 10) 'abstract' is not allowed here.", + "(line 1,col 10) 'public' is not allowed here." + ); + } + + @Test + public void interfaceMethod() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("interface X{" + allModifiers + "int x(){};}")); + assertProblems(result, + "(line 1,col 13) Can have only one of 'public', 'protected', 'private'.", + "(line 1,col 13) Can have only one of 'final', 'abstract'.", + "(line 1,col 13) Can have only one of 'native', 'strictfp'.", + "(line 1,col 13) Cannot be 'abstract' and also 'private', 'static', 'final', 'native', 'strictfp', 'synchronized'.", + "(line 1,col 13) 'transient' is not allowed here.", + "(line 1,col 13) 'volatile' is not allowed here.", + "(line 1,col 13) 'transitive' is not allowed here." + ); + } + + @Test + public void modules() { + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider("open module x {}")); + assertNoProblems(result); + } + + @Test + public void tryWithResourceReference() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("try(a.b.c){}")); + assertNoProblems(result); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java new file mode 100644 index 000000000..e59661170 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/CloneVisitorTest.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.type.Type; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Iterator; + +import static com.github.javaparser.JavaParser.*; +import static org.junit.Assert.assertEquals; + +public class CloneVisitorTest { + CompilationUnit cu; + + @Before + public void setUp() { + cu = new CompilationUnit(); + } + + @After + public void teardown() { + cu = null; + } + + @Test + public void cloneJavaDocTest() { + NodeList<BodyDeclaration<?>> bodyDeclarationList = new NodeList<>(); + bodyDeclarationList.add(new AnnotationMemberDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new ConstructorDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new EnumConstantDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new FieldDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new InitializerDeclaration().setJavadocComment("javadoc")); + bodyDeclarationList.add(new MethodDeclaration().setJavadocComment("javadoc")); + + NodeList<TypeDeclaration<?>> typeDeclarationList = new NodeList<>(); + AnnotationDeclaration annotationDeclaration = new AnnotationDeclaration(); + annotationDeclaration.setName("nnotationDeclarationTest"); + typeDeclarationList.add(annotationDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration2 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration2.setName("emptyTypeDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setJavadocComment("javadoc")); + + EnumDeclaration enumDeclaration = new EnumDeclaration(); + enumDeclaration.setName("enumDeclarationTest"); + typeDeclarationList.add(enumDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration.setName("classOrInterfaceDeclarationTest"); + typeDeclarationList.add(classOrInterfaceDeclaration.setJavadocComment("javadoc")); + + ClassOrInterfaceDeclaration classOrInterfaceDeclaration1 = new ClassOrInterfaceDeclaration(); + classOrInterfaceDeclaration1.setName("emptyTypeDeclarationTest1"); + typeDeclarationList.add(classOrInterfaceDeclaration2.setMembers(bodyDeclarationList)); + + cu.setTypes(typeDeclarationList); + CompilationUnit cuClone = (CompilationUnit) new CloneVisitor().visit(cu, null); + + NodeList<TypeDeclaration<?>> typeDeclarationListClone = cuClone.getTypes(); + Iterator<TypeDeclaration<?>> typeItr = typeDeclarationListClone.iterator(); + TypeDeclaration<?> typeDeclaration; + while (typeItr.hasNext()) { + typeDeclaration = typeItr.next(); + if (typeDeclaration.getMembers() == null) { + assertEquals(typeDeclaration.getComment().get().getContent(), " javadoc"); + } else { + Iterator<BodyDeclaration<?>> bodyItr = typeDeclaration.getMembers().iterator(); + while (bodyItr.hasNext()) { + BodyDeclaration<?> bodyDeclaration = bodyItr.next(); + assertEquals(bodyDeclaration.getComment().get().getContent(), " javadoc"); + } + } + } + } + + @Test + public void cloneAnnotationOnWildcardTypeArgument() { + Type type = parseType("List<@C ? extends Object>").clone(); + assertEquals("List<@C ? extends Object>", type.toString()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java new file mode 100644 index 000000000..679fb1d62 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/HashCodeVisitorTest.java @@ -0,0 +1,24 @@ +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class HashCodeVisitorTest { + @Test + public void testEquals() { + CompilationUnit p1 = JavaParser.parse("class X { }"); + CompilationUnit p2 = JavaParser.parse("class X { }"); + assertEquals(p1.hashCode(), p2.hashCode()); + } + + @Test + public void testNotEquals() { + CompilationUnit p1 = JavaParser.parse("class X { }"); + CompilationUnit p2 = JavaParser.parse("class Y { }"); + assertNotEquals(p1.hashCode(), p2.hashCode()); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java new file mode 100644 index 000000000..ada0c6f98 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/ModifierVisitorTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseExpression; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ModifierVisitorTest { + @Test + public void makeSureParentListsCanBeModified() { + NodeList<StringLiteralExpr> list = new NodeList<>(); + list.add(new StringLiteralExpr("t")); + list.add(new StringLiteralExpr("a")); + list.add(new StringLiteralExpr("b")); + list.add(new StringLiteralExpr("c")); + + list.accept(new ModifierVisitor<Void>() { + @Override + public Visitable visit(final StringLiteralExpr n, final Void arg) { + String v = n.getValue(); + + list.addFirst(new StringLiteralExpr("extra " + v)); + list.remove(new StringLiteralExpr("t")); + + if (v.equals("a")) { + return new StringLiteralExpr("x"); + } + if (v.equals("b")) { + return null; + } + + return n; + } + }, null); + + assertEquals("extra c", list.get(0).getValue()); + assertEquals("extra b", list.get(1).getValue()); + assertEquals("extra a", list.get(2).getValue()); + assertEquals("extra t", list.get(3).getValue()); + assertEquals("x", list.get(4).getValue()); + assertEquals("c", list.get(5).getValue()); + assertEquals(6, list.size()); + } + + @Test + public void binaryExprReturnsLeftExpressionWhenRightSideIsRemoved() { + Expression expression = parseExpression("1+2"); + Visitable result = expression.accept(new ModifierVisitor<Void>() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("1")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("2", result.toString()); + } + + @Test + public void binaryExprReturnsRightExpressionWhenLeftSideIsRemoved() { + final Expression expression = parseExpression("1+2"); + final Visitable result = expression.accept(new ModifierVisitor<Void>() { + public Visitable visit(IntegerLiteralExpr integerLiteralExpr, Void arg) { + if (integerLiteralExpr.getValue().equals("2")) { + return null; + } + return integerLiteralExpr; + } + }, null); + assertEquals("1", result.toString()); + } + + @Test + public void fieldDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("int x=1;"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertEquals(null, result); + } + + @Test + public void variableDeclarationCantSurviveWithoutVariables() { + final BodyDeclaration<?> bodyDeclaration = JavaParser.parseBodyDeclaration("void x() {int x=1;}"); + + final Visitable result = bodyDeclaration.accept(new ModifierVisitor<Void>() { + public Visitable visit(VariableDeclarator x, Void arg) { + return null; + } + }, null); + + assertEquals("void x() {" + EOL + "}", result.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java new file mode 100644 index 000000000..1e2cdf810 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentEqualsVisitorTest.java @@ -0,0 +1,54 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.ast.visitor;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+
+public class NoCommentEqualsVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertTrue(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertFalse(NoCommentEqualsVisitor.equals(p1, p2));
+ }
+}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java new file mode 100644 index 000000000..506566984 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/NoCommentHashCodeVisitorTest.java @@ -0,0 +1,34 @@ +package com.github.javaparser.ast.visitor;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class NoCommentHashCodeVisitorTest {
+
+ @Test
+ public void testEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class X { }");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ }
+
+ @Test
+ public void testEqualsWithDifferentComments() {
+ CompilationUnit p1 = JavaParser.parse("/* a */ class X { /** b */} //c");
+ CompilationUnit p2 = JavaParser.parse("/* b */ class X { } //c");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ assertEquals(p1.getComments().size(), 3);
+ assertEquals(p2.getComments().size(), 2);
+ }
+
+ @Test
+ public void testNotEquals() {
+ CompilationUnit p1 = JavaParser.parse("class X { }");
+ CompilationUnit p2 = JavaParser.parse("class Y { }");
+ assertNotEquals(p1.hashCode(), p2.hashCode());
+ }
+}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java new file mode 100644 index 000000000..53d375336 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/ast/visitor/TreeVisitorTest.java @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.ast.visitor; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.ArrayInitializerExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.SimpleName; +import org.junit.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static org.junit.Assert.assertEquals; + +public class TreeVisitorTest { + @Test + public void isValidBreadthFirstTraversal() { + Expression expression = JavaParser.parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitBreadthFirst(expression); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <(4 + 5)> <2 + 3> <4 + 5> <2> <3> <4> <5> ", result.toString()); + } + + @Test + public void issue743ConcurrentModificationProblem() { + Expression expression = JavaParser.parseExpression("new int[]{1,2,3,4}"); + + StringBuilder result = new StringBuilder(); + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + result.append("<").append(node).append("> "); + } + }; + visitor.visitPreOrder(expression); + System.out.println(result); + } + + @Test + public void isValidPreOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPreOrder(JavaParser.parseExpression("(2+3)+(4+5)")); + assertEquals("<(2 + 3) + (4 + 5)> <(2 + 3)> <2 + 3> <2> <3> <(4 + 5)> <4 + 5> <4> <5> ", result.toString()); + } + + @Test + public void isValidPostOrderTraversal() { + StringBuilder result = new StringBuilder(); + new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }.visitPostOrder(JavaParser.parseExpression("(2+3)+(4+5)")); + assertEquals("<2> <3> <2 + 3> <(2 + 3)> <4> <5> <4 + 5> <(4 + 5)> <(2 + 3) + (4 + 5)> ", result.toString()); + } + + @Test + public void preOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPreOrder(JavaParser.parseExpression("new int[]{1,2,3,4}")); + } + + @Test + public void postOrderConcurrentModificationIsOk() { + new TreeVisitor() { + @Override + public void process(Node node) { + if (node instanceof IntegerLiteralExpr) { + node.getParentNode().ifPresent( + parent -> ((ArrayInitializerExpr) parent).getValues().add(new IntegerLiteralExpr("1"))); + } + } + }.visitPostOrder(JavaParser.parseExpression("new int[]{1,2,3,4}")); + } + + @Test + public void parents() { + CompilationUnit cu = JavaParser.parse("class X{int x=1;}"); + SimpleName x = cu.getClassByName("X").get().getMember(0).asFieldDeclaration().getVariable(0).getName(); + + Node.ParentsVisitor visitor = new Node.ParentsVisitor(x); + assertEquals("x = 1", visitor.next().toString()); + assertEquals("int x = 1;", visitor.next().toString()); + assertEqualsNoEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}", visitor.next().toString()); + assertEqualsNoEol("class X {\n" + + "\n" + + " int x = 1;\n" + + "}\n", visitor.next().toString()); + assertEquals(false, visitor.hasNext()); + } + + @Test + public void isValidDirectChildrenTraversal() { + Expression expression = JavaParser.parseExpression("(2+3)+(4+5)"); + + StringBuilder result = new StringBuilder(); + + TreeVisitor visitor = new TreeVisitor() { + @Override + public void process(Node node) { + result.append("<").append(node).append("> "); + } + }; + + visitor.visitDirectChildren(expression); + assertEquals("<(2 + 3)> <(4 + 5)> ", result.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java new file mode 100644 index 000000000..4e0fe6a6e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/BasicJBehaveTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + + +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.configuration.Configuration; +import org.jbehave.core.configuration.MostUsefulConfiguration; +import org.jbehave.core.failures.FailingUponPendingStep; +import org.jbehave.core.io.LoadFromClasspath; +import org.jbehave.core.io.StoryFinder; +import org.jbehave.core.junit.JUnitStories; +import org.jbehave.core.reporters.Format; +import org.jbehave.core.reporters.StoryReporterBuilder; + +import java.util.List; + +import static org.jbehave.core.io.CodeLocations.codeLocationFromClass; + +abstract class BasicJBehaveTest extends JUnitStories { + + private final String storiesPath; + + public BasicJBehaveTest(String storiesPath) { + this.storiesPath = storiesPath; + JUnitReportingRunner.recommendedControls(configuredEmbedder()); + } + + @Override + public final Configuration configuration() { + return new MostUsefulConfiguration() + // where to find the stories + .useStoryLoader(new LoadFromClasspath(this.getClass())) + // Fails if Steps are not implemented + .usePendingStepStrategy(new FailingUponPendingStep()) + // CONSOLE and HTML reporting + .useStoryReporterBuilder(new StoryReporterBuilder().withDefaultFormats() + .withFormats(Format.CONSOLE, Format.HTML)); + } + + @Override + public final List<String> storyPaths() { + return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), storiesPath, ""); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java new file mode 100644 index 000000000..1ff3619f2 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/CommentParsingTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.CommentParsingSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +@RunWith(JUnitReportingRunner.class) +public class CommentParsingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + return new InstanceStepsFactory(configuration(), new CommentParsingSteps()); + } + + public CommentParsingTest() { + super("**/bdd/comment*.story"); + } +} + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java new file mode 100644 index 000000000..4ecafd764 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ComparingTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.ComparingSteps; +import com.github.javaparser.bdd.steps.SharedSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnitReportingRunner.class) +public class ComparingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map<String, Object> state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ComparingSteps()); + } + + public ComparingTest() { + super("**/bdd/comparing*.story"); + } +} + + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java new file mode 100644 index 000000000..0f24632e9 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ManipulationTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.ManipulationSteps; +import com.github.javaparser.bdd.steps.SharedSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnitReportingRunner.class) +public class ManipulationTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map<String, Object> state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ManipulationSteps(state)); + } + + public ManipulationTest() { + super("**/bdd/manipulation*.story"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java new file mode 100644 index 000000000..d05d57a85 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/ParsingTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.ParsingSteps; +import com.github.javaparser.bdd.steps.SharedSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnitReportingRunner.class) +public class ParsingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map<String, Object> state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new ParsingSteps(state)); + } + + public ParsingTest() { + super("**/bdd/parsing*.story"); + } +} + + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java new file mode 100644 index 000000000..e7f5b2849 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PositionRangeTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.PositionRangeSteps; +import com.github.javaparser.bdd.steps.SharedSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnitReportingRunner.class) +public class PositionRangeTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map<String, Object> state = new HashMap<>(); + + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new PositionRangeSteps()); + } + + public PositionRangeTest() { + super("**/bdd/position_range*.story"); + } +} + + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java new file mode 100644 index 000000000..7540d3b9d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/PrettyPrintingTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.PrettyPrintingSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +@RunWith(JUnitReportingRunner.class) +public class PrettyPrintingTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + return new InstanceStepsFactory(configuration(), new PrettyPrintingSteps()); + } + + public PrettyPrintingTest() { + super("**/bdd/pretty_printing*.story"); + } +} + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java new file mode 100644 index 000000000..784a113de --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/TestUtils.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import java.io.InputStream; + +public class TestUtils { + + public static InputStream getSampleStream(String sampleName) { + InputStream is = TestUtils.class.getClassLoader().getResourceAsStream("com/github/javaparser/bdd/samples/" + + sampleName + ".java"); + if (is == null) { + throw new RuntimeException("Example not found, check your test. Sample name: " + sampleName); + } + return is; + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java new file mode 100644 index 000000000..442c2edcf --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/VisitorTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd; + +import com.github.javaparser.bdd.steps.SharedSteps; +import com.github.javaparser.bdd.steps.VisitorSteps; +import com.github.valfirst.jbehave.junit.monitoring.JUnitReportingRunner; +import org.jbehave.core.steps.InjectableStepsFactory; +import org.jbehave.core.steps.InstanceStepsFactory; +import org.junit.runner.RunWith; + +import java.util.HashMap; +import java.util.Map; + +@RunWith(JUnitReportingRunner.class) +public class VisitorTest extends BasicJBehaveTest { + + @Override + public InjectableStepsFactory stepsFactory() { + Map<String, Object> state = new HashMap<>(); + return new InstanceStepsFactory(configuration(), + new SharedSteps(state), + new VisitorSteps(state)); + } + + public VisitorTest() { + super("**/bdd/visitor*.story"); + } +} + + + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java new file mode 100644 index 000000000..3257c4342 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/CommentParsingSteps.java @@ -0,0 +1,431 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Range; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.*; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.PrettyPrinter; +import com.github.javaparser.printer.PrettyPrinterConfiguration; +import org.jbehave.core.annotations.Alias; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; +import org.jbehave.core.model.ExamplesTable; +import org.jbehave.core.steps.Parameters; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Iterator; +import java.util.Set; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.Range.range; +import static com.github.javaparser.bdd.TestUtils.getSampleStream; +import static com.github.javaparser.bdd.steps.SharedSteps.getMemberByTypeAndPosition; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +public class CommentParsingSteps { + + private CompilationUnit compilationUnit; + private CommentsCollection commentsCollection; + private String sourceUnderTest; + private ParserConfiguration configuration = new ParserConfiguration(); + private PrettyPrinter prettyPrinter = new PrettyPrinter(new PrettyPrinterConfiguration()); + + @Given("the class:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + @When("read sample \"$sampleName\" using encoding \"$encoding\"") + public void givenTheClassWithEncoding(String sampleName, String encoding) throws IOException { + sourceUnderTest = null; + ParseResult<CompilationUnit> parseResult = new JavaParser(new ParserConfiguration()).parse(COMPILATION_UNIT, provider(getSampleStream(sampleName), Charset.forName(encoding))); + commentsCollection = parseResult.getCommentsCollection().orElse(new CommentsCollection()); + } + + @When("the class is parsed by the comment parser") + public void whenTheClassIsParsedByTheCommentParser() throws IOException { + ParseResult<CompilationUnit> parseResult = new JavaParser(new ParserConfiguration()).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + commentsCollection = parseResult.getCommentsCollection().orElse(new CommentsCollection()); + } + + @When("the do not consider annotations as node start for code attribution is $value on the Java parser") + public void whenTheDoNotConsiderAnnotationsAsNodeStartForCodeAttributionIsTrueOnTheJavaParser(boolean value) { + configuration.setDoNotConsiderAnnotationsAsNodeStartForCodeAttribution(value); + } + + @When("the do not assign comments preceding empty lines is $value on the Java parser") + public void whenTheDoNotAssignCommentsPrecedingEmptyLinesIsTrueOnTheJavaParser(boolean value) { + configuration.setDoNotAssignCommentsPrecedingEmptyLines(value); + } + + @When("the class is parsed by the Java parser") + public void whenTheClassIsParsedByTheJavaParser() { + ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + compilationUnit = result.getResult().get(); + } + + @Then("the Java parser cannot parse it because of an error") + public void javaParserCannotParseBecauseOfLexicalErrors() { + ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(sourceUnderTest)); + if (result.isSuccessful()) { + fail("Lexical error expected"); + } + } + + @Then("the total number of comments is $expectedCount") + public void thenTheTotalNumberOfCommentsIs(int expectedCount) { + assertThat(commentsCollection.size(), is(expectedCount)); + } + + private <T extends Comment> T getCommentAt(Set<T> set, int index) { + Iterator<T> iterator = set.iterator(); + T comment = null; + while (index >= 0) { + comment = iterator.next(); + index--; + } + return comment; + } + + @Then("line comment $position is \"$expectedContent\"") + public void thenLineCommentIs(int position, String expectedContent) { + LineComment lineCommentUnderTest = getCommentAt(commentsCollection.getLineComments(), position - 1); + + assertThat(lineCommentUnderTest.getContent(), is(expectedContent)); + } + + @Then("block comment $position is \"$expectedContent\"") + public void thenBlockCommentIs(int position, String expectedContent) { + BlockComment lineCommentUnderTest = getCommentAt(commentsCollection.getBlockComments(), position - 1); + + assertThat(lineCommentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("Javadoc comment $position is \"$expectedContent\"") + public void thenJavadocCommentIs(int position, String expectedContent) { + JavadocComment commentUnderTest = getCommentAt(commentsCollection.getJavadocComments(), position - 1); + + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("the line comments have the following positions: $table") + public void thenTheLineCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new LineComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getLineComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("the block comments have the following positions: $table") + public void thenTheBlockCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new BlockComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getBlockComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("the Javadoc comments have the following positions: $table") + public void thenTheJavadocCommentsHaveTheFollowingPositions(ExamplesTable examplesTable) { + int index = 0; + for (Parameters exampleRow : examplesTable.getRowsAsParameters()) { + Comment expectedLineComment = toComment(exampleRow, new BlockComment()); + Comment lineCommentUnderTest = getCommentAt(commentsCollection.getJavadocComments(), index); + + Range underTestRange = lineCommentUnderTest.getRange().get(); + Range expectedRange = expectedLineComment.getRange().get(); + + assertThat(underTestRange.begin.line, is(expectedRange.begin.line)); + assertThat(underTestRange.begin.column, is(expectedRange.begin.column)); + assertThat(underTestRange.end.line, is(expectedRange.end.line)); + assertThat(underTestRange.end.column, is(expectedRange.end.column)); + index++; + } + } + + @Then("it is printed as:$src") + public void isPrintedAs(String src) { + assertThat(prettyPrinter.print(compilationUnit).trim(), is(src.trim())); + } + + @Then("the compilation unit is not commented") + public void thenTheCompilationUnitIsNotCommented() { + assertEquals(false, compilationUnit.getComment().isPresent()); + } + + @Then("the compilation is commented \"$expectedContent\"") + public void thenTheCompilationIsCommentedCompilationUnitComment(String expectedContent) { + assertThat(compilationUnit.getComment().get().getContent(), is(expectedContent)); + } + + @Then("the compilation unit has $expectedCount contained comments") + public void thenTheCompilationUnitHasContainedComments(int expectedCount) { + assertThat(compilationUnit.getComments().size(), is(expectedCount)); + } + + @Then("the compilation unit has $expectedCount orphan comments") + public void thenTheCompilationUnitHasExpectedCountOrphanComments(int expectedCount) { + assertThat(compilationUnit.getOrphanComments().size(), is(expectedCount)); + } + + @Then("the compilation unit orphan comment $position is \"$expectedContent\"") + public void thenTheCompilationUnitOrphanCommentIs(int position, String expectedContent) { + Comment commentUnderTest = compilationUnit.getOrphanComments().get(position - 1); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("comment $commentPosition in compilation unit is not an orphan") + public void thenCommentInCompilationUnitIsNotAnOrphan(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.isOrphan(), is(false)); + } + + @Then("comment $commentPosition in compilation unit is an orphan") + public void thenCommentInCompilationUnitIsAnOrphan(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.isOrphan(), is(true)); + } + + @Then("comment $commentPosition in compilation unit is \"$expectedContent\"") + public void thenCommentInCompilationUnitIs(int position, String expectedContent) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(position - 1); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("class $position is not commented") + public void thenClassIsNotCommented(int position) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(position - 1); + assertEquals(false, classUnderTest.getComment().isPresent()); + } + + @Then("class $position is commented \"$expectedContent\"") + public void thenClassIsCommented(int position, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getComment().get().getContent(), is(expectedContent)); + } + + @Then("class $position has $expectedCount total contained comments") + public void thenClassHasTotalContainedComments(int position, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("class $position has $expectedCount orphan comment") + @Alias("class $position has $expectedCount orphan comments") + public void thenClassHasOrphanComments(int position, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(position - 1); + assertThat(classUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("class $classPosition orphan comment $commentPosition is \"$expectedContent\"") + public void thenClassOrphanCommentIs(int classPosition, int commentPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + Comment commentUnderTest = classUnderTest.getOrphanComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("method $methodPosition in class $classPosition is commented \"$expectedContent\"") + public void thenMethodInClassIsCommented(int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getComment().get().getContent(), equalToIgnoringWhiteSpace(expectedContent)); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount total contained comments") + public void thenMethodInClassHasTotalContainedComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("comment $commentPosition in method $methodPosition in class $classPosition is \"$expectedContent\"") + public void thenCommentInMethodInClassIs(int commentPosition, int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + Comment commentUnderTest = methodUnderTest.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount orphan comments") + public void thenMethodInClassHasOrphanComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + assertThat(methodUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition has $expectedCount total contained comments") + public void thenBlockStatementInMethodInClassHasTotalContainedComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + assertThat(blockStmtUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition has $expectedCount orphan comments") + public void thenBlockStatementInMethodInClassHasOrphanComments(int methodPosition, int classPosition, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + assertThat(blockStmtUnderTest.getOrphanComments().size(), is(expectedCount)); + } + + @Then("block statement in method $methodPosition in class $classPosition orphan comment $commentPosition is \"$expectedContent\"") + public void thenBlockStatementInMethodInClassIs(int methodPosition, int classPosition, int commentPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + BlockStmt blockStmtUnderTest = methodUnderTest.getBody().orElse(null); + Comment commentUnderTest = blockStmtUnderTest.getOrphanComments().get(commentPosition - 1); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("type of method $methodPosition in class $classPosition is commented \"$expectedContent\"") + public void thenTypeOfMethodInClassIsCommented(int methodPosition, int classPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + MethodDeclaration methodUnderTest = getMemberByTypeAndPosition(classUnderTest, methodPosition - 1, + MethodDeclaration.class); + Comment commentUnderTest = methodUnderTest.getType().getComment().get(); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("field $fieldPosition in class $classPosition contains $expectedCount comments") + public void thenFieldInClassContainsComments(int fieldPosition, int classPosition, int expectedCount) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + assertThat(fieldUnderTest.getAllContainedComments().size(), is(expectedCount)); + } + + @Then("field $fieldPosition in class $classPosition is not commented") + public void thenFieldInClassIsNotCommented(int fieldPosition, int classPosition) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + assertEquals(false, fieldUnderTest.getComment().isPresent()); + } + + @Then("field $fieldPosition in class $classPosition is commented \"$expectedContent\"") + public void thenFieldInClassIsCommented(int fieldPosition, int classPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + Comment commentUnderTest = fieldUnderTest.getComment().get(); + assertThat(commentUnderTest.getContent(), is(equalToIgnoringWhiteSpace(expectedContent))); + } + + @Then("variable $variablePosition value of field $fieldPosition in class $classPosition is commented \"$expectedContent\"") + public void thenVariableValueOfFieldInClassIsCommented(int variablePosition, int fieldPosition, int classPosition, String expectedContent) { + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + VariableDeclarator variableUnderTest = fieldUnderTest.getVariable(variablePosition - 1); + Expression valueUnderTest = variableUnderTest.getInitializer().orElse(null); + Comment commentUnderTest = valueUnderTest.getComment().get(); + assertThat(commentUnderTest.getContent(), is(expectedContent)); + } + + @Then("comment $commentPosition in compilation unit parent is ClassOrInterfaceDeclaration") + public void thenCommentInCompilationUnitParentIsClassOrInterfaceDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getParentNode().get(), instanceOf(ClassOrInterfaceDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is ClassOrInterfaceDeclaration") + public void thenCommentInCompilationUnitCommentedNodeIsClassOrInterfaceDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(ClassOrInterfaceDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is FieldDeclaration") + public void thenCommentInCompilationUnitCommentedNodeIsFieldDeclaration(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(FieldDeclaration.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is IntegerLiteralExpr") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerLiteralExpr(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(IntegerLiteralExpr.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is ExpressionStmt") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerExpressionStmt(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(ExpressionStmt.class)); + } + + @Then("comment $commentPosition in compilation unit commented node is PrimitiveType") + public void thenCommentInCompilationUnitCommentedNodeIsIntegerPrimitiveType(int commentPosition) { + Comment commentUnderTest = compilationUnit.getAllContainedComments().get(commentPosition - 1); + assertThat(commentUnderTest.getCommentedNode().get(), instanceOf(PrimitiveType.class)); + } + + private Comment toComment(Parameters row, Comment comment) { + comment.setRange(range(Integer.parseInt(row.values().get("beginLine")), + Integer.parseInt(row.values().get("beginColumn")), + Integer.parseInt(row.values().get("endLine")), + Integer.parseInt(row.values().get("endColumn")))); + return comment; + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java new file mode 100644 index 000000000..4b789a797 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ComparingSteps.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +public class ComparingSteps { + + private CompilationUnit first; + private CompilationUnit second; + + /* + * Given steps + */ + + @Given("the first class:$classSrc") + public void givenTheFirstClass(String classSrc) { + this.first = JavaParser.parse(classSrc.trim()); + } + + @Given("the second class:$classSrc") + public void givenTheSecondClass(String classSrc) { + this.second = JavaParser.parse(classSrc.trim()); + } + + /* + * Then steps + */ + + @Then("they are equals") + public void thenTheyAreEquals() { + assertThat(first, is(equalTo(second))); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java new file mode 100644 index 000000000..27d81b57f --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ExistenceOfParentNodeVerifier.java @@ -0,0 +1,542 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.HasParentNode; +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +/** + * The <code>ExistenceOfParentNodeVerifier</code> verifies that each node of the compilation unit has a parent set. + */ +class ExistenceOfParentNodeVerifier { + + public void verify(CompilationUnit compilationUnit) throws AssertionError { + new Verifier().visit(compilationUnit, null); + } + + private static class Verifier extends VoidVisitorAdapter<Void> { + private static void assertParentIsSet(HasParentNode<?> n) { + assertThat(n + " has no parent set!", n.getParentNode().orElse(null), is(notNullValue())); + } + + @Override + public void visit(AnnotationDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AnnotationMemberDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayAccessExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayInitializerExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AssertStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(AssignExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BinaryExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BlockComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(BlockStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BooleanLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(BreakStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CastExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CatchClause n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CharLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassOrInterfaceDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ClassOrInterfaceType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(CompilationUnit n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(ConditionalExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ConstructorDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ContinueStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(DoStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(DoubleLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EmptyStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnclosedExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnumConstantDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(EnumDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ExplicitConstructorInvocationStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ExpressionStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(FieldAccessExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(FieldDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ForeachStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ForStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IfStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(InitializerDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(InstanceOfExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IntegerLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(JavadocComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(LabeledStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LineComment n, Void arg) { + super.visit(n, arg); + } + + @Override + public void visit(LambdaExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LongLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MarkerAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MemberValuePair n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodCallExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodReferenceExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NameExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NormalAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NullLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ObjectCreationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(PackageDeclaration n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(Parameter n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(PrimitiveType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(Name n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SimpleName n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationLevel n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(IntersectionType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnionType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ReturnStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SingleMemberAnnotationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(StringLiteralExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SuperExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SwitchEntryStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SwitchStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(SynchronizedStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ThisExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(ThrowStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TryStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(LocalClassDeclarationStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(NodeList n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeParameter n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnaryExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(UnknownType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VariableDeclarationExpr n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VariableDeclarator n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(VoidType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(WhileStmt n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + + @Override + public void visit(WildcardType n, Void arg) { + assertParentIsSet(n); + super.visit(n, arg); + } + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java new file mode 100644 index 000000000..557bf0d60 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ManipulationSteps.java @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.stmt.TryStmt; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import org.jbehave.core.annotations.Alias; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.EnumSet; +import java.util.Map; + +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.JavaParser.parseName; +import static com.github.javaparser.ast.NodeList.nodeList; +import static com.github.javaparser.ast.type.PrimitiveType.*; +import static com.github.javaparser.bdd.steps.SharedSteps.getMethodByPositionAndClassPosition; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; + +public class ManipulationSteps { + + /* Fields used to maintain step state within this step class */ + private BlockStmt blockStmt; + private Statement statement; + private TryStmt tryStmt; + private NodeList<Expression> variableDeclarationExprList; + private ChangeMethodNameToUpperCaseVisitor changeMethodNameToUpperCaseVisitor; + private AddNewIntParameterCalledValueVisitor addNewIntParameterCalledValueVisitor; + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map<String, Object> state; + + public ManipulationSteps(Map<String, Object> state) { + this.state = state; + } + + @Given("a BlockStmt") + public void givenABlockStatement() { + blockStmt = new BlockStmt(); + } + + @Given("a Statement") + public void givenAStatement() { + statement = null; + } + + @Given("a TryStmt") + public void givenATryStmt() { + tryStmt = new TryStmt(); + } + + @Given("a List of VariableDeclarations") + public void givenAListOfVariableDeclarations() { + variableDeclarationExprList = new NodeList<>(); + variableDeclarationExprList.add(new VariableDeclarationExpr()); + variableDeclarationExprList.add(new VariableDeclarationExpr()); + } + + @Given("a ChangeNameToUpperCaseVisitor") + public void givenAChangeNameToUpperCaseVisitor() { + changeMethodNameToUpperCaseVisitor = new ChangeMethodNameToUpperCaseVisitor(); + } + + @Given("a AddNewIntParameterCalledValueVisitor") + public void givenAAddNewParameterCalledValueVisitor() { + addNewIntParameterCalledValueVisitor = new AddNewIntParameterCalledValueVisitor(); + } + + @When("is the String \"$value\" is parsed by the JavaParser using parseBlock") + public void whenIsTheStringIsParsedByTheJavaParser(String value) { + blockStmt = JavaParser.parseBlock(value); + } + + @When("is the String \"$value\" is parsed by the JavaParser using parseStatement") + public void whenIsTheStringIsParsedByTheJavaParserUsingParseStatement(String value) { + statement = JavaParser.parseStatement(value); + } + + @When("the List of VariableDeclarations are set as the resources on TryStmt") + public void whenTheListOfVariableDeclarationsAreSetAsTheResourcesOnTryStmt() { + tryStmt.setResources(variableDeclarationExprList); + } + + @When("empty list is set as the resources on TryStmt") + public void whenNullIsSetAsTheResourcesOnTryStmt() { + tryStmt.setResources(new NodeList<>()); + } + + @When("the package declaration is set to \"$packageName\"") + public void whenThePackageDeclarationIsSetTo(String packageName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + compilationUnit.setPackageDeclaration(new PackageDeclaration(parseName(packageName))); + state.put("cu1", compilationUnit); + } + + @When("a public class called \"$className\" is added to the CompilationUnit") + public void whenAClassCalledIsAddedToTheCompilationUnit(String className) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + TypeDeclaration<?> type = new ClassOrInterfaceDeclaration(EnumSet.of(Modifier.PUBLIC), false, "CreateClass"); + compilationUnit.setTypes(nodeList(type)); + state.put("cu1", compilationUnit); + } + + @When("a public static method called \"$methodName\" returning void is added to class $position in the compilation unit") + public void whenAStaticMethodCalledReturningIsAddedToClassInTheCompilationUnit(String methodName, int position) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + TypeDeclaration<?> type = compilationUnit.getType(position - 1); + EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC); + MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), methodName); + modifiers.add(Modifier.STATIC); + method.setModifiers(modifiers); + type.addMember(method); + state.put("cu1", compilationUnit); + } + + @When("$typeName varargs called \"$parameterName\" are added to method $methodPosition in class $classPosition") + public void whenVarargsCalledAreAddedToMethodInClass(String typeName, String parameterName, int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition) + .addAndGetParameter(typeName, parameterName) + .setVarArgs(true); + } + + @When("a BlockStmt is added to method $methodPosition in class $classPosition") + public void whenABlockStmtIsAddedToMethodInClass(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.setBody(new BlockStmt()); + } + + @When("$className.$fieldName.$methodName(\"$stringValue\"); is added to the body of method $methodPosition in class $classPosition") + public void whenHelloWorldIsAddedToTheBodyOfMethodInClass(String className, String fieldName, String methodName, String stringValue, + int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + NameExpr clazz = new NameExpr(className); + FieldAccessExpr field = new FieldAccessExpr(clazz, fieldName); + MethodCallExpr call = new MethodCallExpr(field, methodName); + call.addArgument(new StringLiteralExpr(stringValue)); + method.getBody().get().addStatement(call); + } + + @When("method $methodPosition in class $classPosition has it's name converted to uppercase") + public void whenMethodInClassHasItsNameConvertedToUppercase(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.setName(method.getNameAsString().toUpperCase()); + } + + @When("method $methodPosition in class $classPosition has an int parameter called \"$paramName\" added") + public void whenMethodInClassHasAnIntArgumentCalledAdded(int methodPosition, int classPosition, String paramName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + method.addParameter(intType(), paramName); + } + + @When("the compilation unit is cloned") + public void whenTheCompilationUnitIsCloned() throws CloneNotSupportedException { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + state.put("cu1", compilationUnit.clone()); + } + + @When("the ChangeNameToUpperCaseVisitor visits to compilation unit") + public void whenTheVisitorVisitsToCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + changeMethodNameToUpperCaseVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @When("the AddNewIntParameterCalledValueVisitor visits to compilation unit") + public void whenTheAddNewParameterCalledValueVisitorVisitsToCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + addNewIntParameterCalledValueVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @Then("is not equal to null") + public void thenIsNotEqualToNull() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertNotEquals(compilationUnit, null); + } + + @Then("is not equal to $value") + public void thenIsNotEqualTo(String value) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertNotEquals(compilationUnit, value); + } + + @Then("Statement $position in BlockStmt toString is \"$expectedContent\"") + public void thenTheBlockStmtContentIs(int position, String expectedContent) { + Statement statementUnderTest = blockStmt.getStatement(position - 1); + assertThat(statementUnderTest.toString(), is(expectedContent)); + } + + @Then("Statement toString is \"$expectedContent\"") + public void thenStatementToStringIsxXy(String expectedContent) { + assertThat(statement.toString(), is(expectedContent)); + } + + @Then("all the VariableDeclarations parent is the TryStmt") + public void thenAllTheVariableDeclarationsParentIsTheTryStmt() { + variableDeclarationExprList.forEach(expr -> assertThat(expr.getParentNode().get(), is(tryStmt))); + } + + @Then("the TryStmt has no child nodes") + public void thenTheTryStmtHasNotChildNodes() { + assertThat(tryStmt.getChildNodes().size(), is(0)); + } + + @Then("method $methodPosition in class $classPosition has the name \"$expectedName\"") + public void thenMethodInClassHasTheName(int methodPosition, int classPosition, String expectedName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + assertThat(method.getNameAsString(), is(expectedName)); + } + + @Then("method $methodPosition in class $classPosition has $expectedCount parameters") + @Alias("method $methodPosition in class $classPosition has $expectedCount parameter") + public void thenMethodInClassHasArguments(int methodPosition, int classPosition, int expectedCount) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + + assertThat(method.getParameters().size(), is(expectedCount)); + } + + @Then("method $methodPosition in class $classPosition parameter $parameterPosition is type int called \"$expectedName\"") + public void thenMethodInClassParameterIsTypeIntCalled(int methodPosition, int classPosition, int parameterPosition, String expectedName) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + Parameter parameter = method.getParameter(parameterPosition - 1); + assertThat(parameter.getType(), is(intType())); + assertThat(parameter.getNameAsString(), is(expectedName)); + } + + private static class ChangeMethodNameToUpperCaseVisitor extends VoidVisitorAdapter<Void> { + @Override + public void visit(MethodDeclaration n, Void arg) { + n.setName(n.getNameAsString().toUpperCase()); + } + } + + private static class AddNewIntParameterCalledValueVisitor extends VoidVisitorAdapter<Void> { + @Override + public void visit(MethodDeclaration n, Void arg) { + n.addParameter(intType(), "value"); + } + } +} + diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java new file mode 100644 index 000000000..01631c6c0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/ParsingSteps.java @@ -0,0 +1,343 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.Statement; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.List; +import java.util.Map; + +import static com.github.javaparser.ParseStart.COMPILATION_UNIT; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.bdd.steps.SharedSteps.getMemberByTypeAndPosition; +import static com.github.javaparser.bdd.steps.SharedSteps.getMethodByPositionAndClassPosition; +import static java.lang.String.format; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.*; + +public class ParsingSteps { + + private Map<String, Object> state; + + public ParsingSteps(Map<String, Object> state) { + this.state = state; + } + + private String sourceUnderTest; + + /* + * Given steps + */ + + @Given("the class:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + + /* + * When steps + */ + + @When("I take the ArrayCreationExpr") + public void iTakeTheArrayCreationExpr() { + setSelectedNodeFromCompilationUnit(ArrayCreationExpr.class); + } + + @When("I take the PackageDeclaration") + public void iTakeThePackageDeclaration() { + setSelectedNodeFromCompilationUnit(PackageDeclaration.class); + } + + @When("I take the ObjectCreationExpr") + public void iTakeTheObjectCreationExpr() throws ClassNotFoundException { + setSelectedNodeFromCompilationUnit(ObjectCreationExpr.class); + } + + /* + * Then steps + */ + + @Then("constructor $constructorPosition in class $classPosition declaration as a String is \"$expectedString\"") + public void thenTheConstructorDeclarationAsAStringIs(int constructorPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + ConstructorDeclaration constructor = (ConstructorDeclaration) clazz.getMember(constructorPosition - 1); + assertThat(constructor.getDeclarationAsString(), is(expectedString)); + } + + @Then("constructor $constructorPosition in class $classPosition declaration short form as a String is \"$expectedString\"") + public void thenConstructorInClassDeclarationShortFormAsAStringIs(int constructorPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + ConstructorDeclaration constructor = (ConstructorDeclaration) clazz.getMember(constructorPosition - 1); + assertThat(constructor.getDeclarationAsString(false, false), is(expectedString)); + } + + @Then("method $methodPosition in class $classPosition declaration as a String is \"$expectedString\"") + public void thenMethod1InClass1DeclarationAsAStringIs(int methodPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + MethodDeclaration method = (MethodDeclaration) clazz.getMember(methodPosition - 1); + assertThat(method.getDeclarationAsString(), is(expectedString)); + } + + @Then("method $methodPosition in class $classPosition declaration as a String short form is \"$expectedString\"") + public void thenMethodInClassDeclarationAsAStringShortFormIs(int methodPosition, int classPosition, String expectedString) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) compilationUnit.getType(classPosition - 1); + MethodDeclaration method = (MethodDeclaration) clazz.getMember(methodPosition - 1); + assertThat(method.getDeclarationAsString(false, false), is(expectedString)); + } + + @Then("field $fieldPosition in class $classPosition contains annotation $annotationPosition value is \"$expectedValue\"") + public void thenFieldInClassContainsAnnotationValueIs(int fieldPosition, int classPosition, int annotationPosition, String expectedValue) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + + TypeDeclaration<?> classUnderTest = compilationUnit.getType(classPosition - 1); + FieldDeclaration fieldUnderTest = getMemberByTypeAndPosition(classUnderTest, fieldPosition - 1, + FieldDeclaration.class); + AnnotationExpr annotationUnderTest = fieldUnderTest.getAnnotation(annotationPosition - 1); + assertThat(annotationUnderTest.getChildNodes().get(1).toString(), is(expectedValue)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is called $expectedName") + public void thenLambdaInClassIsCalled(int statementPosition, int methodPosition, int classPosition, String expectedName) { + Statement statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + VariableDeclarationExpr expression = (VariableDeclarationExpr) ((ExpressionStmt) statement).getExpression(); + VariableDeclarator variableDeclarator = expression.getVariable(0); + assertThat(variableDeclarator.getNameAsString(), is(expectedName)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition body is \"$expectedBody\"") + public void thenLambdaInStatementInMethodInClassBody(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + assertThat(lambdaExpr.getBody().toString(), is(expectedBody)); + } + + @Then("lambda in method call in statement $statementPosition in method $methodPosition in class $classPosition body is \"$expectedBody\"") + public void thenLambdaInMethodCallInStatementInMethodInClassBody(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + ExpressionStmt statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asExpressionStmt(); + VariableDeclarationExpr variableDeclarationExpr = statement.getExpression().asVariableDeclarationExpr(); + VariableDeclarator variableDeclarator = variableDeclarationExpr.getVariable(0); + MethodCallExpr methodCallExpr = (MethodCallExpr) variableDeclarator.getInitializer().orElse(null); + CastExpr castExpr = methodCallExpr.getArgument(0).asCastExpr(); + LambdaExpr lambdaExpr = castExpr.getExpression().asLambdaExpr(); + assertThat(lambdaExpr.getBody().toString(), is(expectedBody)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition block statement is null") + public void thenLambdaInStatementInMethodInClassBlockStatementIsNull(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + BlockStmt blockStmt = lambdaExpr.getBody().asBlockStmt(); + assertEquals(true, blockStmt.getStatements().isEmpty()); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition has parameters with non-null type") + public void thenLambdaInStatementInMethodInClassHasParametersWithNonNullType(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + for (Parameter parameter : lambdaExpr.getParameters()) { + assertThat(parameter.getType(), is(notNullValue())); + } + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition block statement is \"$expectedBody\"") + public void thenLambdaInStatementInMethodInClassBlockStatement(int statementPosition, int methodPosition, int classPosition, + String expectedBody) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + BlockStmt blockStmt = lambdaExpr.getBody().asBlockStmt(); + Statement lambdaStmt = blockStmt.getStatement(0); + assertThat(lambdaStmt.toString(), is(expectedBody)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is parent of contained body") + public void thenLambdaInStatementInMethodInClassIsParentOfContainedBody(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + Statement body = lambdaExpr.getBody(); + assertThat(body.getParentNode().get(), is(lambdaExpr)); + } + + @Then("lambda in statement $statementPosition in method $methodPosition in class $classPosition is parent of contained parameter") + public void thenLambdaInStatementInMethodInClassIsParentOfContainedParameter(int statementPosition, int methodPosition, int classPosition) { + LambdaExpr lambdaExpr = getLambdaExprInStatementInMethodInClass(statementPosition, methodPosition, classPosition); + Parameter parameter = lambdaExpr.getParameter(0); + assertThat(parameter.getParentNode().get(), is(lambdaExpr)); + } + + @Then("method reference in statement $statementPosition in method $methodPosition in class $classPosition scope is $expectedName") + public void thenMethodReferenceInStatementInMethodInClassIsScope(int statementPosition, int methodPosition, + int classPosition, String expectedName) { + ExpressionStmt statementUnderTest = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asExpressionStmt(); + assertEquals(1, statementUnderTest.findAll(MethodReferenceExpr.class).size()); + MethodReferenceExpr methodReferenceUnderTest = statementUnderTest.findFirst(MethodReferenceExpr.class).get(); + assertThat(methodReferenceUnderTest.getScope().toString(), is(expectedName)); + } + + @Then("method reference in statement $statementPosition in method $methodPosition in class $classPosition identifier is $expectedName") + public void thenMethodReferenceInStatementInMethodInClassIdentifierIsCompareByAge(int statementPosition, int methodPosition, + int classPosition, String expectedName) { + Statement statementUnderTest = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + assertEquals(1, statementUnderTest.findAll(MethodReferenceExpr.class).size()); + MethodReferenceExpr methodReferenceUnderTest = statementUnderTest.findFirst(MethodReferenceExpr.class).get(); + assertThat(methodReferenceUnderTest.getIdentifier(), is(expectedName)); + } + + @Then("method $methodPosition class $classPosition is a default method") + public void thenMethodClassIsADefaultMethod(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration methodUnderTest = getMethodByPositionAndClassPosition(compilationUnit, + methodPosition, classPosition); + assertThat(methodUnderTest.isDefault(), is(true)); + } + + @Then("method $methodPosition class $classPosition is not a default method") + public void thenMethodClassIsNotADefaultMethod(int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration methodUnderTest = getMethodByPositionAndClassPosition(compilationUnit, + methodPosition, classPosition); + assertThat(methodUnderTest.isDefault(), is(false)); + } + + private Statement getStatementInMethodInClass(int statementPosition, int methodPosition, int classPosition) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + MethodDeclaration method = getMethodByPositionAndClassPosition(compilationUnit, methodPosition, classPosition); + return method.getBody().get().getStatement(statementPosition - 1); + } + + private LambdaExpr getLambdaExprInStatementInMethodInClass(int statementPosition, int methodPosition, int classPosition) { + Statement statement = getStatementInMethodInClass(statementPosition, methodPosition, classPosition); + VariableDeclarationExpr expression = ((ExpressionStmt) statement).getExpression().asVariableDeclarationExpr(); + VariableDeclarator variableDeclarator = expression.getVariable(0); + return (LambdaExpr) variableDeclarator.getInitializer().orElse(null); + } + + @Then("all nodes refer to their parent") + public void allNodesReferToTheirParent() { + assertAllNodesOfTheCompilationUnitHaveTheirParentSet("cu1"); + } + + @Then("all nodes of the second compilation unit refer to their parent") + public void thenAllNodesOfTheSecondCompilationUnitReferToTheirParent() { + assertAllNodesOfTheCompilationUnitHaveTheirParentSet("cu2"); + } + + private void assertAllNodesOfTheCompilationUnitHaveTheirParentSet(String stateKey) { + CompilationUnit compilationUnit = (CompilationUnit) state.get(stateKey); + ExistenceOfParentNodeVerifier parentVerifier = new ExistenceOfParentNodeVerifier(); + parentVerifier.verify(compilationUnit); + } + + @Then("ThenExpr in the conditional expression of the statement $statementPosition in method $methodPosition in class $classPosition is LambdaExpr") + public void thenLambdaInConditionalExpressionInMethodInClassIsParentOfContainedParameter(int statementPosition, int methodPosition, int classPosition) { + ReturnStmt returnStmt = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asReturnStmt(); + ConditionalExpr conditionalExpr = (ConditionalExpr) returnStmt.getExpression().orElse(null); + assertThat(conditionalExpr.getElseExpr().getClass().getName(), is(LambdaExpr.class.getName())); + } + + @Then("the begin line is $line") + public void thenTheBeginLineIs(int line) { + Node node = (Node) state.get("selectedNode"); + assertEquals(line, node.getBegin().get().line); + } + + @Then("the begin column is $column") + public void thenTheBeginColumnIs(int column) { + Node node = (Node) state.get("selectedNode"); + assertEquals(column, node.getBegin().get().column); + } + + @Then("the end line is $line") + public void thenTheEndLineIs(int line) { + Node node = (Node) state.get("selectedNode"); + assertEquals(line, node.getEnd().get().line); + } + + @Then("the end column is $column") + public void thenTheEndColumnIs(int column) { + Node node = (Node) state.get("selectedNode"); + assertEquals(column, node.getEnd().get().column); + } + + @Then("no errors are reported") + public void thenNoErrorsAreReported() { + // this is present just for readability in the scenario specification + // if the code is not parsed then exceptions are thrown before reaching this step + } + + @Then("the package name is $package") + public void thenThePackageNameIs(String expected) { + PackageDeclaration node = (PackageDeclaration) state.get("selectedNode"); + assertEquals(expected, node.getNameAsString()); + assertEquals(expected, node.getName().toString()); + } + + @Then("the type's diamond operator flag should be $expectedValue") + public void thenTheUsesDiamondOperatorShouldBeBooleanAsString(boolean expectedValue) { + ObjectCreationExpr expr = (ObjectCreationExpr) state.get("selectedNode"); + assertEquals(expectedValue, expr.getType().isUsingDiamondOperator()); + } + + @Then("the Java parser cannot parse it because of an error") + public void javaParserCannotParseBecauseOfLexicalErrors() { + ParseResult<CompilationUnit> result = new JavaParser().parse(COMPILATION_UNIT, provider(sourceUnderTest)); + if (result.isSuccessful()) { + fail("Lexical error expected"); + } + } + + @Then("the assignExpr produced doesn't have a null target") + public void thenTheAssignExprProducedDoesntHaveANullTarget() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + ClassOrInterfaceDeclaration classDeclaration = compilationUnit.getType(0).asClassOrInterfaceDeclaration(); + ConstructorDeclaration ctor = classDeclaration.getMember(1).asConstructorDeclaration(); + ExpressionStmt assignStmt = ctor.getBody().getStatement(0).asExpressionStmt(); + AssignExpr assignExpr = assignStmt.getExpression().asAssignExpr(); + assertNotNull(assignExpr.getTarget()); + assertEquals(NameExpr.class, assignExpr.getTarget().getClass()); + assertEquals(assignExpr.getTarget().asNameExpr().getNameAsString(), "mString"); + } + + private void setSelectedNodeFromCompilationUnit(Class<? extends Node> nodeType) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + List<? extends Node> nodes = compilationUnit.findAll(nodeType); + if (nodes.size() != 1) { + throw new RuntimeException(format("Exactly one %s expected", nodeType.getSimpleName())); + } + state.put("selectedNode", nodes.get(0)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java new file mode 100644 index 000000000..0d7fd896d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PositionRangeSteps.java @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.Position; +import com.github.javaparser.Range; +import org.jbehave.core.annotations.BeforeScenario; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import static com.github.javaparser.Position.pos; +import static com.github.javaparser.Range.range; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PositionRangeSteps { + + private Position position; + private Position secondPosition; + private Range range; + private Range secondRange; + + @BeforeScenario + public void reset() { + position = null; + secondPosition = null; + range = null; + secondRange = null; + } + /* + * Given steps + */ + + @Given("the position $line, $column") + public void givenThePosition(int line, int column) { + this.position = pos(line, column); + } + + @Given("the range $line1, $column1 - $line2, $column2") + public void givenTheRange(int line1, int column1, int line2, int column2) { + this.range = range(line1, column1, line2, column2); + } + + /* + * When steps + */ + + @When("I compare to position $line, $column") + public void iCompareToPosition(int line, int column) { + secondPosition = pos(line, column); + } + + @When("I compare to range $line1, $column1 - $line2, $column2") + public void whenICompareToRange(int line1, int column1, int line2, int column2) { + this.secondRange = range(line1, column1, line2, column2); + } + + /* + * Then steps + */ + + @Then("the positions are equal") + public void thenThePositionsAreEqual() { + assertTrue(position.equals(secondPosition)); + } + + @Then("it is after the {first|} position") + public void thenItIsAfterTheFirstPosition() { + if (secondPosition != null) { + assertTrue(secondPosition.isAfter(position)); + } else { + assertTrue(secondRange.isAfter(position)); + } + } + + @Then("it is before the {first|} position") + public void thenItIsBeforeTheFirstPosition() { + if (secondPosition != null) { + assertTrue(secondPosition.isBefore(position)); + } else { + assertTrue(secondRange.isBefore(position)); + } + } + + @Then("the positions are not equal") + public void thenThePositionsAreNotEqual() { + assertFalse(position.equals(secondPosition)); + } + + @Then("it is not after the {first|} position") + public void thenItIsNotAfterTheFirstPosition() { + assertFalse(secondPosition.isAfter(position)); + } + + @Then("it is not before the {first|} position") + public void thenItIsNotBeforeTheFirstPosition() { + assertFalse(secondPosition.isBefore(position)); + } + + @Then("the ranges are equal") + public void theRangesAreEqual() { + assertTrue(range.equals(secondRange)); + } + + @Then("it is contained in the first range") + public void itIsContainedInTheFirstRange() { + assertTrue(range.contains(secondRange)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java new file mode 100644 index 000000000..1dcd802a5 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/PrettyPrintingSteps.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.ParseException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.visitor.ModifierVisitor; +import com.github.javaparser.printer.PrettyPrinterConfiguration; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.readerToString; +import static org.junit.Assert.assertEquals; + +public class PrettyPrintingSteps { + + private Node resultNode; + private String sourceUnderTest; + + @Given("the {class|compilation unit|expression|block|statement|import|annotation|body|class body|interface body}:$classSrc") + public void givenTheClass(String classSrc) { + this.sourceUnderTest = classSrc.trim(); + } + + @Given("the {class|compilation unit|expression|block|statement|import|annotation|body|class body|interface body} in the file \"$classFile\"") + public void givenTheClassInTheFile(String classFile) throws URISyntaxException, IOException, ParseException { + URL url = getClass().getResource("../samples/" + classFile); + sourceUnderTest = readerToString(new FileReader(new File(url.toURI()))).trim(); + } + + @When("the {class|compilation unit} is parsed by the Java parser") + public void whenTheClassIsParsedByTheJavaParser() { + resultNode = parse(sourceUnderTest); + } + + @When("the expression is parsed by the Java parser") + public void whenTheExpressionIsParsedByTheJavaParser() { + resultNode = parseExpression(sourceUnderTest); + } + + @When("the block is parsed by the Java parser") + public void whenTheBlockIsParsedByTheJavaParser() { + resultNode = parseBlock(sourceUnderTest); + } + + @When("the statement is parsed by the Java parser") + public void whenTheStatementIsParsedByTheJavaParser() { + resultNode = parseStatement(sourceUnderTest); + } + + @When("the import is parsed by the Java parser") + public void whenTheImportIsParsedByTheJavaParser() { + resultNode = parseImport(sourceUnderTest); + } + + @When("the annotation is parsed by the Java parser") + public void whenTheAnnotationIsParsedByTheJavaParser() { + resultNode = parseAnnotation(sourceUnderTest); + } + + @When("the annotation body declaration is parsed by the Java parser") + public void whenTheBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseAnnotationBodyDeclaration(sourceUnderTest); + } + + @When("the class body declaration is parsed by the Java parser") + public void whenTheClassBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseBodyDeclaration(sourceUnderTest); + } + + @When("the interface body declaration is parsed by the Java parser") + public void whenTheInterfaceBodyDeclarationIsParsedByTheJavaParser() { + resultNode = parseBodyDeclaration(sourceUnderTest); + } + + @When("the class is visited by an empty ModifierVisitorAdapter") + public void whenTheClassIsVisitedByAnEmptyModifierVisitorAdapter() { + (new ModifierVisitor<Void>() { + }).visit((CompilationUnit) resultNode, null); + } + + @Then("it is printed as:$src") + public void isPrintedAs(String src) { + assertEquals(src.trim(), resultNode.toString().trim()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java new file mode 100644 index 000000000..53b7c4434 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/SharedSteps.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import org.hamcrest.CoreMatchers; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Map; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; +import static org.junit.Assert.assertThat; + +public class SharedSteps { + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map<String, Object> state; + + public SharedSteps(Map<String, Object> state) { + this.state = state; + } + + /* + * Given steps + */ + + @Given("a CompilationUnit") + public void givenACompilationUnit() { + state.put("cu1", new CompilationUnit()); + } + + @Given("a second CompilationUnit") + public void givenASecondCompilationUnit() { + state.put("cu2", new CompilationUnit()); + } + + /* + * When steps + */ + + @When("the following source is parsed:$classSrc") + public void whenTheFollowingSourceIsParsed(String classSrc) { + state.put("cu1", JavaParser.parse(classSrc.trim())); + } + + @When("the following source is parsed (trimming space):$classSrc") + public void whenTheFollowingSourceIsParsedTrimmingSpace(String classSrc) { + state.put("cu1", JavaParser.parse(classSrc.trim())); + } + + @When("the following sources is parsed by the second CompilationUnit:$classSrc") + public void whenTheFollowingSourcesIsParsedBytTheSecondCompilationUnit(String classSrc) { + state.put("cu2", JavaParser.parse(classSrc.trim())); + } + + @When("file \"$fileName\" is parsed") + public void whenTheJavaFileIsParsed(String fileName) throws IOException, URISyntaxException { + URL url = getClass().getResource("../samples/" + fileName); + CompilationUnit compilationUnit = JavaParser.parse(new File(url.toURI())); + state.put("cu1", compilationUnit); + } + + @Then("the CompilationUnit is equal to the second CompilationUnit") + public void thenTheCompilationUnitIsEqualToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit, is(equalTo(compilationUnit2))); + } + + @Then("the CompilationUnit has the same hashcode to the second CompilationUnit") + public void thenTheCompilationUnitHasTheSameHashcodeToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit.hashCode(), is(equalTo(compilationUnit2.hashCode()))); + } + + @Then("the CompilationUnit is not equal to the second CompilationUnit") + public void thenTheCompilationUnitIsNotEqualToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit, not(equalTo(compilationUnit2))); + } + + @Then("the CompilationUnit has a different hashcode to the second CompilationUnit") + public void thenTheCompilationUnitHasADifferentHashcodeToTheSecondCompilationUnit() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) state.get("cu2"); + + assertThat(compilationUnit.hashCode(), not(equalTo(compilationUnit2.hashCode()))); + } + + @Then("the expected source should be:$classSrc") + public void thenTheExpectedSourcesShouldBe(String classSrc) { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + assertThat(compilationUnit.toString(), CoreMatchers.is(equalToIgnoringWhiteSpace(classSrc))); + } + + public static <T extends BodyDeclaration<?>> T getMemberByTypeAndPosition(TypeDeclaration<?> typeDeclaration, int position, Class<T> typeClass) { + int typeCount = 0; + for (BodyDeclaration<?> declaration : typeDeclaration.getMembers()) { + if (declaration.getClass().equals(typeClass)) { + if (typeCount == position) { + return (T) declaration; + } + typeCount++; + } + } + throw new IllegalArgumentException("No member " + typeClass + " at position: " + position); + } + + public static MethodDeclaration getMethodByPositionAndClassPosition(CompilationUnit compilationUnit, + int methodPosition, int classPosition) { + TypeDeclaration<?> type = compilationUnit.getType(classPosition - 1); + + int memberCount = 0; + int methodCount = 0; + for (BodyDeclaration<?> bodyDeclaration : type.getMembers()) { + if (bodyDeclaration instanceof MethodDeclaration) { + if (methodCount == methodPosition - 1) { + return (MethodDeclaration) type.getMember(memberCount); + } + methodCount++; + } + memberCount++; + } + throw new IllegalArgumentException("Method not found at position " + methodPosition + "in class " + classPosition); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java new file mode 100644 index 000000000..ba20eaf16 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/steps/VisitorSteps.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.steps; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.visitor.CloneVisitor; +import com.github.javaparser.ast.visitor.GenericListVisitorAdapter; +import com.github.javaparser.ast.visitor.GenericVisitorAdapter; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import com.github.javaparser.bdd.visitors.PositionTestVisitor; +import org.jbehave.core.annotations.Given; +import org.jbehave.core.annotations.Then; +import org.jbehave.core.annotations.When; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class VisitorSteps { + + /* Fields used to maintain step state within this step class */ + private VoidVisitorAdapter<AtomicReference<String>> toUpperCaseVariableNameVisitor; + private VoidVisitorAdapter<AtomicReference<String>> collectVariableNameVisitor; + private PositionTestVisitor positionTestVisitor; + private GenericVisitorAdapter<String, Void> nameReturningVisitor; + private GenericListVisitorAdapter<String, Void> allNameReturningVisitor; + private AtomicReference<String> collectedVariableName; + private String returnedVariableName; + private List<String> returnedVariableNames; + + /* Map that maintains shares state across step classes. If manipulating the objects in the map you must update the state */ + private Map<String, Object> state; + + public VisitorSteps(Map<String, Object> state) { + this.state = state; + } + + @Given("a VoidVisitorAdapter with a visit method that changes variable names to uppercase") + public void givenAVoidVisitorAdapterWithAVisitMethodThatChangesVariableNamesToUppercase() { + toUpperCaseVariableNameVisitor = new VoidVisitorAdapter<AtomicReference<String>>() { + @Override + public void visit(VariableDeclarator n, AtomicReference<String> arg) { + n.setName(n.getNameAsString().toUpperCase()); + } + }; + } + + @Given("a VoidVisitorAdapter with a visit method and collects the variable names") + public void givenAVoidVisitorAdapterWithAVisitMethodThatCollectsTheVariableName() { + collectVariableNameVisitor = new VoidVisitorAdapter<AtomicReference<String>>() { + @Override + public void visit(VariableDeclarator n, AtomicReference<String> arg) { + arg.set(arg.get() + n.getName() + ";"); + } + + @Override + public void visit(Parameter n, AtomicReference<String> arg) { + arg.set(arg.get() + n.getName() + ";"); + } + }; + } + + @Given("a GenericVisitorAdapter with a visit method that returns variable names") + public void givenAGenericVisitorAdapterWithAVisitMethodThatReturnsVariableNames() { + nameReturningVisitor = new GenericVisitorAdapter<String, Void>() { + @Override + public String visit(VariableDeclarator n, Void arg) { + return n.getNameAsString(); + } + }; + } + + @Given("a GenericListVisitorAdapter with a visit method that returns all variable names") + public void givenAGenericListVisitorAdapterWithAVisitMethodThatReturnsAllVariableNames() { + allNameReturningVisitor = new GenericListVisitorAdapter<String, Void>() { + @Override + public List<String> visit(VariableDeclarator n, Void arg) { + return Collections.singletonList(n.getNameAsString()); + } + }; + } + + @Given("a VoidVisitorAdapter with a visit method that asserts sensible line positions") + public void givenAVoidVisitorAdapterWithAVisitMethodThatAssertsSensibleLinePositions() { + positionTestVisitor = new PositionTestVisitor(); + } + + @When("the CompilationUnit is cloned to the second CompilationUnit") + public void whenTheSecondCompilationUnitIsCloned() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + CompilationUnit compilationUnit2 = (CompilationUnit) compilationUnit.accept(new CloneVisitor(), null); + state.put("cu2", compilationUnit2); + } + + @When("the CompilationUnit is visited by the to uppercase visitor") + public void whenTheCompilationUnitIsVisitedByTheVistor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + toUpperCaseVariableNameVisitor.visit(compilationUnit, null); + state.put("cu1", compilationUnit); + } + + @When("the CompilationUnit is visited by the variable name collector visitor") + public void whenTheCompilationUnitIsVisitedByTheVariableNameCollectorVisitor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + collectedVariableName = new AtomicReference<>(""); + collectVariableNameVisitor.visit(compilationUnit, collectedVariableName); + } + + @When("the CompilationUnit is visited by the visitor that returns variable names") + public void whenTheCompilationUnitIsVisitedByTheVisitorThatReturnsVariableNames() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + returnedVariableName = nameReturningVisitor.visit(compilationUnit, null); + } + + @When("the CompilationUnit is visited by the visitor that returns all variable names") + public void whenTheCompilationUnitIsVisitedByTheVisitorThatReturnsAllVariableNames() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + returnedVariableNames = allNameReturningVisitor.visit(compilationUnit, null); + } + + @When("the CompilationUnit is visited by the PositionTestVisitor") + public void whenTheCompilationUnitIsVisitedByThePositionTestVisitor() { + CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1"); + compilationUnit.accept(positionTestVisitor, null); + } + + @Then("the collected variable name is \"$nameUnderTest\"") + public void thenTheCollectedVariableNameIs(String nameUnderTest) { + assertThat(collectedVariableName.get(), is(nameUnderTest)); + } + + @Then("the return variable name is \"$nameUnderTest\"") + public void thenTheReturnVariableNameIs(String nameUnderTest) { + assertThat(returnedVariableName, is(nameUnderTest)); + } + + @Then("the first return variable name is \"$nameUnderTest\"") + public void thenTheFirstReturnVariableNameIs(String nameUnderTest) { + assertThat(returnedVariableNames.get(0), is(nameUnderTest)); + } + + @Then("the total number of nodes visited is $expectedCount") + public void thenTheTotalNumberOfNodesVisitedIs(int expectedCount) { + assertThat(positionTestVisitor.getNumberOfNodesVisited(), is(expectedCount)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java b/javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java new file mode 100644 index 000000000..bfa331fd8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/bdd/visitors/PositionTestVisitor.java @@ -0,0 +1,553 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.bdd.visitors; + +import com.github.javaparser.Position; +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.BlockComment; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.*; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.core.Is.is; + +public class PositionTestVisitor extends VoidVisitorAdapter<Object> { + + private int numberOfNodesVisited; + + @Override + public void visit(final AnnotationDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final AnnotationMemberDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayAccessExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayCreationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ArrayInitializerExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final AssertStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final AssignExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BinaryExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BlockComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BlockStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BooleanLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final BreakStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CastExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CatchClause n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(LambdaExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(MethodReferenceExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(TypeExpr n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CharLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ClassExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ClassOrInterfaceDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final ClassOrInterfaceType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final CompilationUnit n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ConditionalExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ConstructorDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ContinueStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final DoStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final DoubleLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EmptyStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnclosedExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnumConstantDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final EnumDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final ExplicitConstructorInvocationStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ExpressionStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final FieldAccessExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final FieldDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ForeachStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ForStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IfStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final InitializerDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final InstanceOfExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IntegerLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final JavadocComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LabeledStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LineComment n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LongLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MarkerAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MemberValuePair n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MethodCallExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final MethodDeclaration n, final Object arg) { + doTest(n); + doTest(n.getName()); + super.visit(n, arg); + } + + @Override + public void visit(final NameExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final NormalAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final NullLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ObjectCreationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final PackageDeclaration n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final Parameter n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final PrimitiveType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final Name n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(SimpleName n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(ArrayCreationLevel n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final IntersectionType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(UnionType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ReturnStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SingleMemberAnnotationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final StringLiteralExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SuperExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SwitchEntryStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SwitchStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final SynchronizedStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ThisExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final ThrowStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final TryStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final LocalClassDeclarationStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final TypeParameter n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final UnaryExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VariableDeclarationExpr n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VariableDeclarator n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final VoidType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final WhileStmt n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(final WildcardType n, final Object arg) { + doTest(n); + super.visit(n, arg); + } + + @Override + public void visit(UnknownType n, Object arg) { + doTest(n); + super.visit(n, arg); + } + + private void doTest(final Node node) { + Position begin = node.getRange().get().begin; + Position end = node.getRange().get().end; + assertThat(begin.line, is(greaterThanOrEqualTo(0))); + assertThat(begin.column, is(greaterThanOrEqualTo(0))); + assertThat(end.line, is(greaterThanOrEqualTo(0))); + assertThat(end.column, is(greaterThanOrEqualTo(0))); + + if (begin.line == end.line) { + assertThat(begin.column, is(lessThanOrEqualTo(end.column))); + } else { + assertThat(begin.line, is(lessThanOrEqualTo(end.line))); + } + numberOfNodesVisited++; + } + + public int getNumberOfNodesVisited() { + return numberOfNodesVisited; + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java new file mode 100644 index 000000000..aff535476 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/ClassOrInterfaceDeclarationBuildersTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; +import java.util.function.Function; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ClassOrInterfaceDeclarationBuildersTest { + CompilationUnit cu; + + @Before + public void setup() { + cu = new CompilationUnit(); + } + + @After + public void teardown() { + cu = null; + } + + @Test + public void testAddExtends() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + testClass.addExtendedType(List.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + List.class.getName() + ";" + EOL, + cu.getImport(0).toString()); + assertEquals(1, testClass.getExtendedTypes().size()); + assertEquals(List.class.getSimpleName(), testClass.getExtendedTypes(0).getNameAsString()); + } + + @Test + public void testAddImplements() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + testClass.addImplementedType(Function.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + Function.class.getName() + ";" + EOL, + cu.getImport(0).toString()); + assertEquals(1, testClass.getImplementedTypes().size()); + assertEquals(Function.class.getSimpleName(), testClass.getImplementedTypes(0).getNameAsString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java new file mode 100644 index 000000000..11ac7e957 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/CompilationUnitBuildersTest.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; + +public class CompilationUnitBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + public void testAddImport() { + cu.addImport(Map.class); + cu.addImport(Map.class); + cu.addImport(List.class); + assertEquals(2, cu.getImports().size()); + cu.addImport("myImport"); + assertEquals(3, cu.getImports().size()); + assertEquals("import " + Map.class.getName() + ";" + EOL, cu.getImport(0).toString()); + assertEquals("import " + List.class.getName() + ";" + EOL, cu.getImport(1).toString()); + assertEquals("import myImport;" + EOL, cu.getImport(2).toString()); + } + + class testInnerClass { + + } + + @Test + public void testAddImportAnonymousClass() { + cu.addImport(testInnerClass.class); + assertEquals("import " + testInnerClass.class.getName().replace("$", ".") + ";" + EOL, + cu.getImport(0).toString()); + } + + @Test(expected = RuntimeException.class) + public void testAddImportInnerClass() { + Object anonymous = new Object() { + + }; + cu.addImport(anonymous.getClass()); + } + + @Test + public void testAddClass() { + ClassOrInterfaceDeclaration myClassDeclaration = cu.addClass("testClass", Modifier.PRIVATE); + assertEquals(1, cu.getTypes().size()); + assertEquals("testClass", cu.getType(0).getNameAsString()); + assertEquals(ClassOrInterfaceDeclaration.class, cu.getType(0).getClass()); + assertTrue(myClassDeclaration.isPrivate()); + assertFalse(myClassDeclaration.isInterface()); + } + + @Test + public void testAddInterface() { + ClassOrInterfaceDeclaration myInterfaceDeclaration = cu.addInterface("testInterface"); + assertEquals(1, cu.getTypes().size()); + assertEquals("testInterface", cu.getType(0).getNameAsString()); + assertTrue(myInterfaceDeclaration.isPublic()); + assertEquals(ClassOrInterfaceDeclaration.class, cu.getType(0).getClass()); + assertTrue(myInterfaceDeclaration.isInterface()); + } + + @Test + public void testAddEnum() { + EnumDeclaration myEnumDeclaration = cu.addEnum("test"); + assertEquals(1, cu.getTypes().size()); + assertEquals("test", cu.getType(0).getNameAsString()); + assertTrue(myEnumDeclaration.isPublic()); + assertEquals(EnumDeclaration.class, cu.getType(0).getClass()); + } + + @Test + public void testAddAnnotationDeclaration() { + AnnotationDeclaration myAnnotationDeclaration = cu.addAnnotationDeclaration("test"); + assertEquals(1, cu.getTypes().size()); + assertEquals("test", cu.getType(0).getNameAsString()); + assertTrue(myAnnotationDeclaration.isPublic()); + assertEquals(AnnotationDeclaration.class, cu.getType(0).getClass()); + } + + @Test + public void testGetClassByName() { + assertEquals(cu.addClass("test"), cu.getClassByName("test").get()); + } + + @Test + public void testGetInterfaceByName() { + assertEquals(cu.addInterface("test"), cu.getInterfaceByName("test").get()); + } + + @Test + public void testGetEnumByName() { + assertEquals(cu.addEnum("test"), cu.getEnumByName("test").get()); + } + + @Test + public void testGetAnnotationDeclarationByName() { + assertEquals(cu.addAnnotationDeclaration("test"), cu.getAnnotationDeclarationByName("test").get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java new file mode 100644 index 000000000..048307d75 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/EnumDeclarationBuildersTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.EnumDeclaration; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.function.Function; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class EnumDeclarationBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + public void testAddImplements() { + EnumDeclaration testEnum = cu.addEnum("test"); + testEnum.addImplementedType(Function.class); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + Function.class.getName() + ";" + EOL, + cu.getImport(0).toString()); + assertEquals(1, testEnum.getImplementedTypes().size()); + assertEquals(Function.class.getSimpleName(), testEnum.getImplementedTypes(0).getNameAsString()); + } + + @Test + public void testAddEnumConstant() { + EnumDeclaration testEnum = cu.addEnum("test"); + testEnum.addEnumConstant("MY_ENUM_CONSTANT"); + assertEquals(1, testEnum.getEntries().size()); + assertEquals("MY_ENUM_CONSTANT", testEnum.getEntry(0).getNameAsString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java new file mode 100644 index 000000000..7824addd1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/FieldDeclarationBuildersTest.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +import static com.github.javaparser.ast.type.PrimitiveType.intType; +import static org.junit.Assert.assertEquals; + +public class FieldDeclarationBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass"); + private EnumDeclaration testEnum = cu.addEnum("testEnum"); + + @Test(expected = IllegalStateException.class) + public void testOrphanFieldGetter() { + new FieldDeclaration().createGetter(); + } + + @Test(expected = IllegalStateException.class) + public void testOrphanFieldSetter() { + new FieldDeclaration().createSetter(); + } + + @Test + public void testCreateGetterInAClass() { + testClass.addPrivateField(int.class, "myField").createGetter(); + assertEquals(2, testClass.getMembers().size()); + assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass()); + List<MethodDeclaration> methodsWithName = testClass.getMethodsByName("getMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration getter = methodsWithName.get(0); + assertEquals("getMyField", getter.getNameAsString()); + assertEquals("int", getter.getType().toString()); + assertEquals(ReturnStmt.class, getter.getBody().get().getStatement(0).getClass()); + } + + @Test + public void testCreateSetterInAClass() { + testClass.addPrivateField(int.class, "myField").createSetter(); + assertEquals(2, testClass.getMembers().size()); + assertEquals(MethodDeclaration.class, testClass.getMember(1).getClass()); + List<MethodDeclaration> methodsWithName = testClass.getMethodsByName("setMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration setter = methodsWithName.get(0); + assertEquals("setMyField", setter.getNameAsString()); + assertEquals("int", setter.getParameter(0).getType().toString()); + assertEquals(ExpressionStmt.class, setter.getBody().get().getStatement(0).getClass()); + assertEquals("this.myField = myField;", setter.getBody().get().getStatement(0).toString()); + } + + @Test + public void testCreateGetterInEnum() { + testEnum.addPrivateField(int.class, "myField").createGetter(); + assertEquals(2, testEnum.getMembers().size()); + assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass()); + List<MethodDeclaration> methodsWithName = testEnum.getMethodsByName("getMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration getter = methodsWithName.get(0); + assertEquals("getMyField", getter.getNameAsString()); + assertEquals("int", getter.getType().toString()); + assertEquals(ReturnStmt.class, getter.getBody().get().getStatement(0).getClass()); + } + + @Test + public void testCreateSetterInEnum() { + testEnum.addPrivateField(int.class, "myField").createSetter(); + assertEquals(2, testEnum.getMembers().size()); + assertEquals(MethodDeclaration.class, testEnum.getMember(1).getClass()); + List<MethodDeclaration> methodsWithName = testEnum.getMethodsByName("setMyField"); + assertEquals(1, methodsWithName.size()); + MethodDeclaration setter = methodsWithName.get(0); + assertEquals("setMyField", setter.getNameAsString()); + assertEquals("int", setter.getParameter(0).getType().toString()); + assertEquals(ExpressionStmt.class, setter.getBody().get().getStatement(0).getClass()); + assertEquals("this.myField = myField;", setter.getBody().get().getStatement(0).toString()); + } + + @Test(expected = IllegalStateException.class) + public void testCreateGetterWithANonValidField() { + FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField"); + myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField")); + myPrivateField.createGetter(); + } + + @Test(expected = IllegalStateException.class) + public void testCreateSetterWithANonValidField() { + FieldDeclaration myPrivateField = testClass.addPrivateField(int.class, "myField"); + myPrivateField.getVariables().add(new VariableDeclarator(intType(), "secondField")); + myPrivateField.createSetter(); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java new file mode 100644 index 000000000..b72201631 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithAnnotationsBuildersTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class NodeWithAnnotationsBuildersTest { + private CompilationUnit cu = new CompilationUnit(); + private ClassOrInterfaceDeclaration testClass = cu.addClass("testClass"); ; + + @interface hey { + + } + + @Test + public void testAddAnnotation() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals("import com.github.javaparser.builders.NodeWithAnnotationsBuildersTest.hey;", cu.getImport(0).toString().trim()); + assertEquals(1, testClass.getAnnotations().size()); + assertEquals(annotation, testClass.getAnnotation(0)); + assertEquals(NormalAnnotationExpr.class, testClass.getAnnotation(0).getClass()); + } + + @Test + public void testAddMarkerAnnotation() { + testClass.addMarkerAnnotation("test"); + assertEquals(1, testClass.getAnnotations().size()); + } + + @Test + public void testAddSingleMemberAnnotation() { + testClass.addSingleMemberAnnotation("test", "value"); + assertEquals(1, testClass.getAnnotations().size()); + assertEquals("value", testClass.getAnnotation(0).asSingleMemberAnnotationExpr().getMemberValue().toString()); + } + + @Test + public void testIsAnnotationPresent() { + testClass.addMarkerAnnotation(hey.class); + assertTrue(testClass.isAnnotationPresent(hey.class)); + } + + @Test + public void testGetAnnotationByName() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals(annotation, testClass.getAnnotationByName("hey").get()); + } + + @Test + public void testGetAnnotationByClass() { + NormalAnnotationExpr annotation = testClass.addAndGetAnnotation(hey.class); + assertEquals(annotation, testClass.getAnnotationByClass(hey.class).get()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java new file mode 100644 index 000000000..4ac1f0681 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithMembersBuildersTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import org.junit.Test; + +import java.util.List; + +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class NodeWithMembersBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + private final ClassOrInterfaceDeclaration classDeclaration = cu.addClass("test"); + + @Test + public void testAddField() { + FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addField, classDeclaration.getMember(0)); + assertEquals("fieldName", addField.getVariable(0).getNameAsString()); + } + + @Test + public void testAddMethod() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addMethod, classDeclaration.getMember(0)); + assertEquals("foo", addMethod.getNameAsString()); + } + + @Test + public void testAddCtor() { + ConstructorDeclaration addCtor = classDeclaration.addConstructor(Modifier.PUBLIC); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(addCtor, classDeclaration.getMember(0)); + assertEquals(classDeclaration.getName(), addCtor.getName()); + } + + @Test + public void testAddInitializers() { + classDeclaration.addInitializer(); + assertEquals(1, classDeclaration.getMembers().size()); + assertEquals(InitializerDeclaration.class, classDeclaration.getMember(0).getClass()); + + classDeclaration.addStaticInitializer(); + assertEquals(2, classDeclaration.getMembers().size()); + assertEquals(InitializerDeclaration.class, classDeclaration.getMember(0).getClass()); + } + + @Test + public void testGetMethodsWithName() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC); + MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload"); + List<MethodDeclaration> methodsByName = classDeclaration.getMethodsByName("foo"); + assertEquals(2, methodsByName.size()); + assertTrue(methodsByName.contains(addMethod)); + assertTrue(methodsByName.contains(addMethod2)); + } + + @Test + public void testGetMethods() { + MethodDeclaration addMethod = classDeclaration.addMethod("foo", Modifier.PUBLIC); + MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload"); + + List<MethodDeclaration> methods = classDeclaration.getMethods(); + + assertEquals(2, methods.size()); + assertTrue(methods.contains(addMethod)); + assertTrue(methods.contains(addMethod2)); + } + + @Test + public void testGetMethodsWithParameterTypes() { + classDeclaration.addMethod("foo", Modifier.PUBLIC); + MethodDeclaration addMethod2 = classDeclaration.addMethod("foo", Modifier.PUBLIC).addParameter(int.class, "overload"); + ClassOrInterfaceType type = parseClassOrInterfaceType("List"); + type.setTypeArguments(parseClassOrInterfaceType("String")); + MethodDeclaration methodWithListParam = classDeclaration.addMethod("fooList", Modifier.PUBLIC).addParameter(type, "overload"); + MethodDeclaration addMethod3 = classDeclaration.addMethod("foo2", Modifier.PUBLIC).addParameter(int.class, "overload"); + + List<MethodDeclaration> methodsByParam = classDeclaration.getMethodsByParameterTypes(int.class); + assertEquals(2, methodsByParam.size()); + assertTrue(methodsByParam.contains(addMethod2)); + assertTrue(methodsByParam.contains(addMethod3)); + List<MethodDeclaration> methodsByParam2 = classDeclaration.getMethodsByParameterTypes("List<String>"); + assertEquals(1, methodsByParam2.size()); + assertTrue(methodsByParam2.contains(methodWithListParam)); + } + + @Test + public void testGetFieldWithName() { + FieldDeclaration addField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE); + classDeclaration.addField(float.class, "secondField", Modifier.PRIVATE); + FieldDeclaration fieldByName = classDeclaration.getFieldByName("fieldName").get(); + assertEquals(addField, fieldByName); + } + + @Test + public void testGetFields() { + FieldDeclaration firstField = classDeclaration.addField(int.class, "fieldName", Modifier.PRIVATE); + FieldDeclaration secondField = classDeclaration.addField(float.class, "secondField", Modifier.PRIVATE); + + List<FieldDeclaration> fields = classDeclaration.getFields(); + + assertTrue(fields.contains(firstField)); + assertTrue(fields.contains(secondField)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java new file mode 100644 index 000000000..87d0a2553 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithParametersBuildersTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.List; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class NodeWithParametersBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + public void testAddParameter() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC); + addMethod.addParameter(int.class, "yay"); + Parameter myNewParam = addMethod.addAndGetParameter(List.class, "myList"); + assertEquals(1, cu.getImports().size()); + assertEquals("import " + List.class.getName() + ";" + EOL, cu.getImport(0).toString()); + assertEquals(2, addMethod.getParameters().size()); + assertEquals("yay", addMethod.getParameter(0).getNameAsString()); + assertEquals("List", addMethod.getParameter(1).getType().toString()); + assertEquals(myNewParam, addMethod.getParameter(1)); + } + + @Test + public void testGetParamByName() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC); + Parameter addAndGetParameter = addMethod.addAndGetParameter(int.class, "yay"); + assertEquals(addAndGetParameter, addMethod.getParameterByName("yay").get()); + } + + @Test + public void testGetParamByType() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC); + Parameter addAndGetParameter = addMethod.addAndGetParameter(int.class, "yay"); + assertEquals(addAndGetParameter, addMethod.getParameterByType("int").get()); + assertEquals(addAndGetParameter, addMethod.getParameterByType(int.class).get()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java new file mode 100644 index 000000000..79756065a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/builders/NodeWithThrownExceptionsBuildersTest.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.builders; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static org.junit.Assert.assertEquals; + +public class NodeWithThrownExceptionsBuildersTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + public void testThrows() { + MethodDeclaration addMethod = cu.addClass("test").addMethod("foo", Modifier.PUBLIC); + addMethod.addThrownException(IllegalStateException.class); + assertEquals(1, addMethod.getThrownExceptions().size()); + assertEquals(true, addMethod.isThrown(IllegalStateException.class)); + addMethod.addThrownException(parseClassOrInterfaceType("Test")); + assertEquals(2, addMethod.getThrownExceptions().size()); + assertEquals("Test", addMethod.getThrownException(1).toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java new file mode 100644 index 000000000..59740b3b0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocExtractorTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.javadoc; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseProblemException; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import org.apache.commons.io.Charsets; +import org.junit.Test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; + +public class JavadocExtractorTest { + + @Test + public void canParseAllJavadocsInJavaParser() throws FileNotFoundException { + processDir(new File("..")); + } + + private void processFile(File file) throws FileNotFoundException { + try { + CompilationUnit cu = JavaParser.parse(file, StandardCharsets.UTF_8); + new VoidVisitorAdapter<Object>() { + @Override + public void visit(JavadocComment n, Object arg) { + super.visit(n, arg); + n.parse(); + } + }.visit(cu, null); + } catch (ParseProblemException e) { + System.err.println("ERROR PROCESSING "+ file); + } + } + + private void processDir(File dir) throws FileNotFoundException { + for (File child : dir.listFiles()) { + if (child.isFile() && child.getName().endsWith(".java")) { + processFile(child); + } else if (child.isDirectory()) { + processDir(child); + } + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java new file mode 100644 index 000000000..7377dfb86 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/JavadocTest.java @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.javadoc; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.javadoc.description.JavadocDescription; +import com.github.javaparser.javadoc.description.JavadocDescriptionElement; +import com.github.javaparser.javadoc.description.JavadocInlineTag; +import org.junit.Test; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JavadocTest { + + @Test + public void toTextForEmptyJavadoc() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + assertEquals("", javadoc.toText()); + } + + @Test + public void toTextForJavadocWithTwoLinesOfJustDescription() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line")); + assertEquals("first line" + EOL + "second line" + EOL, javadoc.toText()); + } + + @Test + public void toTextForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line")); + javadoc.addBlockTag("foo", "something useful"); + assertEquals("first line" + EOL + "second line" + EOL + EOL + "@foo something useful" + EOL, javadoc.toText()); + } + + @Test + public void toCommentForEmptyJavadoc() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + assertEquals(new JavadocComment("" + EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + public void toCommentorJavadocWithTwoLinesOfJustDescription() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line")); + assertEquals(new JavadocComment("" + EOL + "\t\t * first line" + EOL + "\t\t * second line" + EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + public void toCommentForJavadocWithTwoLinesOfJustDescriptionAndOneBlockTag() { + Javadoc javadoc = new Javadoc(JavadocDescription.parseText("first line" + EOL + "second line")); + javadoc.addBlockTag("foo", "something useful"); + assertEquals(new JavadocComment("" + EOL + "\t\t * first line" + EOL + "\t\t * second line" + EOL + "\t\t * " + EOL + "\t\t * @foo something useful" + EOL + "\t\t "), javadoc.toComment("\t\t")); + } + + @Test + public void descriptionAndBlockTagsAreRetrievable() { + Javadoc javadoc = JavaParser.parseJavadoc("first line" + EOL + "second line" + EOL + EOL + "@param node a node" + EOL + "@return result the result"); + assertEquals("first line" + EOL + "second line", javadoc.getDescription().toText()); + assertEquals(2, javadoc.getBlockTags().size()); + } + + @Test + public void inlineTagsAreParsable() { + String docText = + "Returns the {@link TOFilename}s of all files that existed during the requested" + EOL + + "{@link TOVersion}." + EOL + + "" + EOL + + "@param versionID the id of the {@link TOVersion}." + EOL + + "@return the filenames" + EOL + + "@throws InvalidIDException if the {@link IPersistence} doesn't recognize the given versionID." + EOL; + String javadoc = JavaParser.parseJavadoc(docText).toText(); + assertTrue(javadoc.contains("{@link TOVersion}")); + } + + @Test + public void emptyLinesBetweenBlockTagsGetsFiltered() { + String comment = " * The type of the Object to be mapped." + EOL + + " * This interface maps the given Objects to existing ones in the database and" + EOL + + " * saves them." + EOL + + " * " + EOL + + " * @author censored" + EOL + + " * " + EOL + + " * @param <T>" + EOL; + Javadoc javadoc = JavaParser.parseJavadoc(comment); + assertEquals(2, javadoc.getBlockTags().size()); + } + + @Test + public void blockTagModificationWorks() { + Javadoc javadoc = new Javadoc(new JavadocDescription()); + + assertEquals(0, javadoc.getBlockTags().size()); + JavadocBlockTag blockTag = new JavadocBlockTag(JavadocBlockTag.Type.RETURN, "a value"); + javadoc.addBlockTag(blockTag); + + assertEquals(1, javadoc.getBlockTags().size()); + assertEquals(blockTag, javadoc.getBlockTags().get(0)); + + assertEquals(blockTag, javadoc.getBlockTags().remove(0)); + assertEquals(0, javadoc.getBlockTags().size()); + } + + @Test + public void descriptionModificationWorks() { + JavadocDescription description = new JavadocDescription(); + + assertEquals(0, description.getElements().size()); + + JavadocDescriptionElement inlineTag = new JavadocInlineTag("inheritDoc", JavadocInlineTag.Type.INHERIT_DOC, ""); + assertTrue(description.addElement(inlineTag)); + + assertEquals(1, description.getElements().size()); + assertEquals(inlineTag, description.getElements().get(0)); + + assertEquals(inlineTag, description.getElements().remove(0)); + assertEquals(0, description.getElements().size()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java new file mode 100644 index 000000000..128eb61f2 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/javadoc/description/JavadocInlineTagTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2017 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.javadoc.description; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class JavadocInlineTagTest { + + @Test + public void javadocInlineTagShouldPersistCustomTagNames() { + String tag = JavadocInlineTag.fromText("{@foo something}").toText(); + + assertEquals(tag, "@foo something"); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java b/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java new file mode 100644 index 000000000..b09651f7d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/manual/BulkParseTest.java @@ -0,0 +1,120 @@ +package com.github.javaparser.manual; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.Problem; +import com.github.javaparser.utils.CodeGenerationUtils; +import com.github.javaparser.utils.Log; +import com.github.javaparser.utils.SourceRoot; +import com.github.javaparser.utils.SourceZip; +import org.junit.Test; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.SourceRoot.Callback.Result.DONT_SAVE; +import static com.github.javaparser.utils.TestUtils.download; +import static com.github.javaparser.utils.TestUtils.temporaryDirectory; +import static java.util.Comparator.comparing; + +public class BulkParseTest { + /** + * Running this will download a version of the OpenJDK, unzip it, and parse it. If it throws a stack overflow + * exception, increase the JVM's stack size. + */ + public static void main(String[] args) throws IOException { + Log.setAdapter(new Log.StandardOutStandardErrorAdapter()); + // This contains all kinds of test cases so it will lead to a lot of errors: + new BulkParseTest().parseOpenJdkLangToolsRepository(); + // This contains the JDK source code, so it should have zero errors: + new BulkParseTest().parseJdkSrcZip(); + } + + private void parseOpenJdkLangToolsRepository() throws IOException { + Path workdir = CodeGenerationUtils.mavenModuleRoot(BulkParseTest.class).resolve(Paths.get(temporaryDirectory(), "javaparser_bulkparsetest")); + workdir.toFile().mkdirs(); + Path openJdkZipPath = workdir.resolve("langtools.zip"); + if (Files.notExists(openJdkZipPath)) { + Log.info("Downloading JDK langtools"); + /* Found by choosing a tag here: http://hg.openjdk.java.net/jdk9/jdk9/langtools/tags + then copying the "zip" link to the line below: */ + download(new URL("http://hg.openjdk.java.net/jdk10/jdk10/langtools/archive/19293ea3999f.zip"), openJdkZipPath); + } + bulkTest(new SourceZip(openJdkZipPath), "openjdk_src_repo_test_results.txt", new ParserConfiguration().setLanguageLevel(JAVA_10)); + } + + private void parseJdkSrcZip() throws IOException { + // This is where Ubuntu stores the contents of package openjdk-8-src + Path path = Paths.get("/usr/lib/jvm/openjdk-9/src.zip"); + bulkTest(new SourceZip(path), "openjdk_src_zip_test_results.txt", new ParserConfiguration().setLanguageLevel(JAVA_9)); + } + + @Test + public void parseOwnSourceCode() throws IOException { + bulkTest( + new SourceRoot(CodeGenerationUtils.mavenModuleRoot(BulkParseTest.class).resolve("..")), + "javaparser_test_results.txt", + new ParserConfiguration().setLanguageLevel(JAVA_9)); + } + + public void bulkTest(SourceRoot sourceRoot, String testResultsFileName, ParserConfiguration configuration) throws IOException { + sourceRoot.setParserConfiguration(configuration); + TreeMap<Path, List<Problem>> results = new TreeMap<>(comparing(o -> o.toString().toLowerCase())); + sourceRoot.parseParallelized((localPath, absolutePath, result) -> { + if (!localPath.toString().contains("target")) { + if (!result.isSuccessful()) { + results.put(localPath, result.getProblems()); + } + } + return DONT_SAVE; + }); + writeResults(results, testResultsFileName); + } + + public void bulkTest(SourceZip sourceRoot, String testResultsFileName, ParserConfiguration configuration) throws IOException { + sourceRoot.setParserConfiguration(configuration); + TreeMap<Path, List<Problem>> results = new TreeMap<>(comparing(o -> o.toString().toLowerCase())); + sourceRoot.parse((path, result) -> { + if (!path.toString().contains("target")) { + if (!result.isSuccessful()) { + results.put(path, result.getProblems()); + } + } + }); + writeResults(results, testResultsFileName); + } + + private void writeResults(TreeMap<Path, List<Problem>> results, String testResultsFileName) throws IOException { + Log.info("Writing results..."); + + Path testResults = CodeGenerationUtils.mavenModuleRoot(BulkParseTest.class).resolve(Paths.get("..", "javaparser-testing", "src", "test", "resources", "com", "github", "javaparser", "bulk_test_results")).normalize(); + testResults.toFile().mkdirs(); + testResults = testResults.resolve(testResultsFileName); + + int problemTotal = 0; + try (BufferedWriter writer = Files.newBufferedWriter(testResults)) { + for (Map.Entry<Path, List<Problem>> file : results.entrySet()) { + writer.write(file.getKey().toString().replace("\\", "/")); + writer.newLine(); + for (Problem problem : file.getValue()) { + writer.write(problem.getVerboseMessage()); + writer.newLine(); + problemTotal++; + } + writer.newLine(); + } + writer.write(f("%s problems in %s files", problemTotal, results.size())); + } + + Log.info("Results are in %s", testResults); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java new file mode 100644 index 000000000..06a586caf --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/BaseNodeMetaModelTest.java @@ -0,0 +1,25 @@ +package com.github.javaparser.metamodel; + +import com.github.javaparser.ast.expr.StringLiteralExpr; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +class TestMetaModel extends BaseNodeMetaModel { + + public TestMetaModel() { + super(Optional.empty(), StringLiteralExpr.class, "stri", "com.japa", true, true); + } +} + +public class BaseNodeMetaModelTest { + @Test + public void testGetters() { + TestMetaModel test = new TestMetaModel(); + + assertEquals("testMetaModel", test.getMetaModelFieldName()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java new file mode 100644 index 000000000..2333d8101 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/metamodel/PropertyMetaModelTest.java @@ -0,0 +1,45 @@ +package com.github.javaparser.metamodel; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.BodyDeclaration; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class PropertyMetaModelTest { + @Test + public void whenPropertyIsVerySimpleThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", int.class, Optional.empty(), false, false, false, false, false); + assertEquals("int", bert.getTypeName()); + assertEquals("int", bert.getTypeNameGenerified()); + assertEquals("int", bert.getTypeNameForGetter()); + assertEquals("int", bert.getTypeNameForSetter()); + } + + @Test + public void whenPropertyIsVeryComplexThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", BodyDeclaration.class, Optional.empty(), true, false, true, false, true); + assertEquals("BodyDeclaration", bert.getTypeName()); + assertEquals("BodyDeclaration<?>", bert.getTypeNameGenerified()); + assertEquals("Optional<NodeList<BodyDeclaration<?>>>", bert.getTypeNameForGetter()); + assertEquals("NodeList<BodyDeclaration<?>>", bert.getTypeNameForSetter()); + } + + @Test + public void whenPropertyIsAnEnumThenTypeInfoIsCorrect() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, false, true, false); + assertEquals("Modifier", bert.getTypeName()); + assertEquals("Modifier", bert.getTypeNameGenerified()); + assertEquals("EnumSet<Modifier>", bert.getTypeNameForGetter()); + assertEquals("EnumSet<Modifier>", bert.getTypeNameForSetter()); + } + + @Test + public void metaModelFieldName() { + PropertyMetaModel bert = new PropertyMetaModel(null, "bert", Modifier.class, Optional.empty(), false, false, false, true, false); + assertEquals("bertPropertyMetaModel", bert.getMetaModelFieldName()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java b/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java new file mode 100644 index 000000000..80ebe557e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/modules/ModuleDeclarationTest.java @@ -0,0 +1,181 @@ +package com.github.javaparser.modules; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.JavaToken; +import com.github.javaparser.ParseStart; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; +import com.github.javaparser.ast.modules.*; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import org.junit.Test; + +import static com.github.javaparser.GeneratedJavaParserConstants.IDENTIFIER; +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.JavaParser.parseName; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_9; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.Utils.EOL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + +public class ModuleDeclarationTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + + private final CompilationUnit parse(String code) { + return javaParser.parse(ParseStart.COMPILATION_UNIT, provider(code)).getResult().get(); + } + + @Test + public void moduleInfoKeywordsAreSeenAsIdentifiers() { + CompilationUnit cu = parse("class module { }"); + JavaToken moduleToken = cu.getClassByName("module").get().getName().getTokenRange().get().getBegin(); + assertEquals(IDENTIFIER, moduleToken.getKind()); + } + + @Test + public void issue988RequireTransitiveShouldRequireAModuleCalledTransitive() { + CompilationUnit cu = parse("module X { requires transitive; }"); + ModuleRequiresStmt requiresTransitive = (ModuleRequiresStmt) cu.getModule().get().getModuleStmts().get(0); + assertEquals("transitive", requiresTransitive.getNameAsString()); + assertEquals(IDENTIFIER, requiresTransitive.getName().getTokenRange().get().getBegin().getKind()); + } + + @Test + public void jlsExample1() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires transitive static G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + ModuleDeclaration module = cu.getModule().get(); + assertEquals("M.N", module.getNameAsString()); + assertEquals(false, module.isOpen()); + assertThat(module.getAnnotations()).containsExactly( + new SingleMemberAnnotationExpr(new Name("Foo"), new IntegerLiteralExpr("1")), + new SingleMemberAnnotationExpr(new Name("Foo"), new IntegerLiteralExpr("2")), + new MarkerAnnotationExpr(new Name("Bar"))); + + ModuleRequiresStmt moduleRequiresStmt = module.getModuleStmts().get(0).asModuleRequiresStmt(); + assertThat(moduleRequiresStmt.getNameAsString()).isEqualTo("A.B"); + assertThat(moduleRequiresStmt.getModifiers()).isEmpty(); + + ModuleExportsStmt moduleExportsStmt = module.getModuleStmts().get(5).asModuleExportsStmt(); + assertThat(moduleExportsStmt.getNameAsString()).isEqualTo("R.S"); + assertThat(moduleExportsStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2")); + + ModuleOpensStmt moduleOpensStmt = module.getModuleStmts().get(7).asModuleOpensStmt(); + assertThat(moduleOpensStmt.getNameAsString()).isEqualTo("R.S"); + assertThat(moduleOpensStmt.getModuleNames()).containsExactly(parseName("T1.U1"), parseName("T2.U2")); + + ModuleUsesStmt moduleUsesStmt = module.getModuleStmts().get(8).asModuleUsesStmt(); + assertThat(moduleUsesStmt.getType().toString()).isEqualTo("V.W"); + + ModuleProvidesStmt moduleProvidesStmt = module.getModuleStmts().get(9).asModuleProvidesStmt(); + assertThat(moduleProvidesStmt.getType().toString()).isEqualTo("X.Y"); + assertThat(moduleProvidesStmt.getWithTypes()).containsExactly( + new ClassOrInterfaceType(parseClassOrInterfaceType("Z1"), "Z2"), + new ClassOrInterfaceType(parseClassOrInterfaceType("Z3"), "Z4")); + + } + + @Test + public void jlsExample2HasAnOpenModule() { + CompilationUnit cu = parse("open module M.N {}"); + + ModuleDeclaration module = cu.getModule().get(); + assertEquals("M.N", module.getNameAsString()); + assertEquals(true, module.isOpen()); + } + + @Test + public void testPrettyPrinting() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires transitive static G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + assertEquals( + "@Foo(1) @Foo(2) @Bar " + EOL + + "module M.N {" + EOL + + " requires A.B;" + EOL + + " requires transitive C.D;" + EOL + + " requires static E.F;" + EOL + + " requires static transitive G.H;" + EOL + + " exports P.Q;" + EOL + + " exports R.S to T1.U1, T2.U2;" + EOL + + " opens P.Q;" + EOL + + " opens R.S to T1.U1, T2.U2;" + EOL + + " uses V.W;" + EOL + + " provides X.Y with Z1.Z2, Z3.Z4;" + EOL + + "}" + EOL, cu.toString()); + + } + + @Test + public void testCsmPrinting() { + CompilationUnit cu = parse( + "@Foo(1) @Foo(2) @Bar " + + "open module M.N {" + + " requires A.B;" + + " requires transitive C.D;" + + " requires static E.F;" + + " requires transitive static G.H;" + + "" + + " exports P.Q;" + + " exports R.S to T1.U1, T2.U2;" + + "" + + " opens P.Q;" + + " opens R.S to T1.U1, T2.U2;" + + "" + + " uses V.W;" + + " provides X.Y with Z1.Z2, Z3.Z4;" + + "}"); + + assertEquals( + "@Foo(1) @Foo(2) @Bar" + EOL + + "open module M.N {" + EOL + + " requires A.B;" + EOL + + " requires transitive C.D;" + EOL + + " requires static E.F;" + EOL + + " requires static transitive G.H;" + EOL + + " exports P.Q;" + EOL + + " exports R.S to T1.U1, T2.U2;" + EOL + + " opens P.Q;" + EOL + + " opens R.S to T1.U1, T2.U2;" + EOL + + " uses V.W;" + EOL + + " provides X.Y with Z1.Z2, Z3.Z4;" + EOL + + "}" + EOL, ConcreteSyntaxModel.genericPrettyPrint(cu)); + + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java new file mode 100644 index 000000000..af47a9d9d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelAcceptanceTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.utils.CodeGenerationUtils; +import com.github.javaparser.utils.TestUtils; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Path; + +import static org.junit.Assert.assertEquals; + +public class ConcreteSyntaxModelAcceptanceTest { + private final Path rootDir = CodeGenerationUtils.mavenModuleRoot(ConcreteSyntaxModelAcceptanceTest.class).resolve("src/test/test_sourcecode"); + + private String prettyPrint(Node node) { + return ConcreteSyntaxModel.genericPrettyPrint(node); + } + + private String prettyPrintedExpectation(String name) throws IOException { + return TestUtils.readResource("com/github/javaparser/printer/" + name + "_prettyprinted"); + } + + @Test + public void printingExamplePrettyPrintVisitor() throws IOException { + CompilationUnit cu = JavaParser.parse(rootDir.resolve("com/github/javaparser/printer/PrettyPrintVisitor.java")); + assertEquals(prettyPrintedExpectation("PrettyPrintVisitor"), prettyPrint(cu)); + } + + @Test + public void printingExampleJavaConcepts() throws IOException { + CompilationUnit cu = JavaParser.parse(rootDir.resolve("com/github/javaparser/printer/JavaConcepts.java")); + assertEquals(prettyPrintedExpectation("JavaConcepts"), prettyPrint(cu)); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java new file mode 100644 index 000000000..b08f90b92 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/ConcreteSyntaxModelTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.ClassExpr; +import org.junit.Test; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class ConcreteSyntaxModelTest { + + private String print(Node node) { + return ConcreteSyntaxModel.genericPrettyPrint(node); + } + + @Test + public void printSimpleClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + @Test + public void printArrayClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo[].class"); + assertEquals("Foo[].class", print(expr)); + } + + @Test + public void printGenericClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo<String>.class"); + assertEquals("Foo<String>.class", print(expr)); + } + + @Test + public void printSimplestClass() { + Node node = JavaParser.parse("class A {}"); + assertEquals("class A {" + EOL + + "}" + EOL, print(node)); + } + + @Test + public void printAClassWithField() { + Node node = JavaParser.parse("class A { int a; }"); + assertEquals("class A {" + EOL + + EOL + + " int a;" + EOL + + "}" + EOL, print(node)); + } + + @Test + public void printParameters() { + Node node = JavaParser.parseBodyDeclaration("int x(int y, int z) {}"); + assertEquals("int x(int y, int z) {" + EOL + "}", print(node)); + } + + @Test + public void printReceiverParameter() { + Node node = JavaParser.parseBodyDeclaration("int x(X A.B.this, int y, int z) {}"); + assertEquals("int x(X A.B.this, int y, int z) {" + EOL + "}", print(node)); + } + + @Test + public void printAnEmptyInterface() { + Node node = JavaParser.parse("interface A {}"); + assertEquals("interface A {" + EOL + + "}" + EOL, print(node)); + } + + @Test + public void printAnEmptyInterfaceWithModifier() { + Node node = JavaParser.parse("public interface A {}"); + assertEquals("public interface A {" + EOL + + "}" + EOL, print(node)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java new file mode 100644 index 000000000..ca11465a6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/DotPrinterTest.java @@ -0,0 +1,79 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+
+public class DotPrinterTest {
+ @Test
+ public void testWithType() {
+ String expectedOutput = "digraph {" + System.lineSeparator();
+ expectedOutput += "n0 [label=\"root (MethodCallExpr)\"];" + System.lineSeparator();
+ expectedOutput += "n1 [label=\"name (SimpleName)\"];" + System.lineSeparator();
+ expectedOutput += "n0 -> n1;" + System.lineSeparator();
+ expectedOutput += "n2 [label=\"identifier='x'\"];" + System.lineSeparator();
+ expectedOutput += "n1 -> n2;" + System.lineSeparator();
+ expectedOutput += "n3 [label=\"arguments\"];" + System.lineSeparator();
+ expectedOutput += "n0 -> n3;" + System.lineSeparator();
+ expectedOutput += "n4 [label=\"argument (IntegerLiteralExpr)\"];" + System.lineSeparator();
+ expectedOutput += "n3 -> n4;" + System.lineSeparator();
+ expectedOutput += "n5 [label=\"value='1'\"];" + System.lineSeparator();
+ expectedOutput += "n4 -> n5;" + System.lineSeparator();
+ expectedOutput += "n6 [label=\"argument (IntegerLiteralExpr)\"];" + System.lineSeparator();
+ expectedOutput += "n3 -> n6;" + System.lineSeparator();
+ expectedOutput += "n7 [label=\"value='1'\"];" + System.lineSeparator();
+ expectedOutput += "n6 -> n7;" + System.lineSeparator();
+ expectedOutput += "}";
+
+ DotPrinter dotPrinter = new DotPrinter(true);
+ Expression expression = JavaParser.parseExpression("x(1,1)");
+ String output = dotPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithoutType() {
+ String expectedOutput = "digraph {" + System.lineSeparator();
+ expectedOutput += "n0 [label=\"root\"];" + System.lineSeparator();
+ expectedOutput += "n1 [label=\"operator='PLUS'\"];" + System.lineSeparator();
+ expectedOutput += "n0 -> n1;" + System.lineSeparator();
+ expectedOutput += "n2 [label=\"left\"];" + System.lineSeparator();
+ expectedOutput += "n0 -> n2;" + System.lineSeparator();
+ expectedOutput += "n3 [label=\"value='1'\"];" + System.lineSeparator();
+ expectedOutput += "n2 -> n3;" + System.lineSeparator();
+ expectedOutput += "n4 [label=\"right\"];" + System.lineSeparator();
+ expectedOutput += "n0 -> n4;" + System.lineSeparator();
+ expectedOutput += "n5 [label=\"value='1'\"];" + System.lineSeparator();
+ expectedOutput += "n4 -> n5;" + System.lineSeparator();
+ expectedOutput += "}";
+
+ DotPrinter dotPrinter = new DotPrinter(false);
+ Expression expression = JavaParser.parseExpression("1+1");
+ String output = dotPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java new file mode 100644 index 000000000..7e26254a4 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/JsonPrinterTest.java @@ -0,0 +1,75 @@ +package com.github.javaparser.printer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.expr.Expression; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.*; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.io.BufferedWriter; + +public class JsonPrinterTest { + @Test + public void testWithType() { + JsonPrinter jsonPrinter = new JsonPrinter(true); + Expression expression = parseExpression("x(1,1)"); + + String output = jsonPrinter.output(expression); + + assertEquals("{\"type\":\"MethodCallExpr\",\"name\":{\"type\":\"SimpleName\",\"identifier\":\"x\"},\"arguments\":[{\"type\":\"IntegerLiteralExpr\",\"value\":\"1\"},{\"type\":\"IntegerLiteralExpr\",\"value\":\"1\"}]}", output); + } + + @Test + public void testWithoutType() { + JsonPrinter jsonPrinter = new JsonPrinter(false); + Expression expression = parseExpression("1+1"); + + String output = jsonPrinter.output(expression); + + assertEquals("{\"operator\":\"PLUS\",\"left\":{\"value\":\"1\"},\"right\":{\"value\":\"1\"}}", output); + } + + @Test + public void testEscaping() { + JsonPrinter jsonPrinter = new JsonPrinter(false); + CompilationUnit expression = parse("class X {//hi\"" + EOL + "int x;}"); + + String output = jsonPrinter.output(expression); + + assertEquals("{\"types\":[{\"isInterface\":\"false\",\"name\":{\"identifier\":\"X\",\"comment\":{\"content\":\"hi\\\"\"}},\"members\":[{\"variables\":[{\"name\":{\"identifier\":\"x\"},\"type\":{\"type\":\"INT\"}}]}]}]}", output); + } + + @Test + public void issue1338() { + String code = "class Test {" + + " public void method() {" + + " String.format(\"I'm using %s\", \"JavaParser\");" + + " }" + + "}"; + CompilationUnit unit = parse(code); + JsonPrinter printer = new JsonPrinter(true); + printer.output(unit); + } + + @Test + public void issue1421() { + // Handle multi-line strings in JSON output + String code = "/* \n" + + "* Some comment\n" + + "*/\n" + + "public class Test {}"; + CompilationUnit unit = parse(code); + JsonPrinter printer = new JsonPrinter(true); + + String output = printer.output(unit); + + assertEquals("{\"type\":\"CompilationUnit\",\"types\":[{\"type\":\"ClassOrInterfaceDeclaration\",\"isInterface\":\"false\",\"name\":{\"type\":\"SimpleName\",\"identifier\":\"Test\"},\"comment\":{\"type\":\"BlockComment\",\"content\":\" \\n* Some comment\\n\"}}]}", output); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java new file mode 100644 index 000000000..df1168ed1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrintVisitorTest.java @@ -0,0 +1,277 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.CastExpr; +import com.github.javaparser.ast.expr.ClassExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.Type; +import org.junit.Test; + +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; + +public class PrettyPrintVisitorTest { + + @Test + public void getMaximumCommonTypeWithoutAnnotations() { + VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a[], b[]"); + assertEquals("int[]", vde1.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[][] a[], b[]"); + assertEquals("int[][][]", vde2.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde3 = JavaParser.parseVariableDeclarationExpr("int[][] a, b[]"); + assertEquals("int[][]", vde3.getMaximumCommonType().get().toString()); + } + + @Test + public void getMaximumCommonTypeWithAnnotations() { + VariableDeclarationExpr vde1 = JavaParser.parseVariableDeclarationExpr("int a @Foo [], b[]"); + assertEquals("int", vde1.getMaximumCommonType().get().toString()); + + VariableDeclarationExpr vde2 = JavaParser.parseVariableDeclarationExpr("int[]@Foo [] a[], b[]"); + assertEquals("int[] @Foo [][]", vde2.getMaximumCommonType().get().toString()); + } + + private String print(Node node) { + return new PrettyPrinter().print(node); + } + + @Test + public void printSimpleClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo.class"); + assertEquals("Foo.class", print(expr)); + } + + @Test + public void printArrayClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo[].class"); + assertEquals("Foo[].class", print(expr)); + } + + @Test + public void printGenericClassExpr() { + ClassExpr expr = JavaParser.parseExpression("Foo<String>.class"); + assertEquals("Foo<String>.class", print(expr)); + } + + @Test + public void printSimplestClass() { + Node node = JavaParser.parse("class A {}"); + assertEquals("class A {" + EOL + + "}" + EOL, print(node)); + } + + @Test + public void printAClassWithField() { + Node node = JavaParser.parse("class A { int a; }"); + assertEquals("class A {" + EOL + + EOL + + " int a;" + EOL + + "}" + EOL, print(node)); + } + + @Test + public void printAReceiverParameter() { + Node node = JavaParser.parseBodyDeclaration("int x(@O X A.B.this, int y) { }"); + assertEquals("int x(@O X A.B.this, int y) {" + EOL + "}", print(node)); + } + + @Test + public void printLambdaIntersectionTypeAssignment() { + String code = "class A {" + EOL + + " void f() {" + EOL + + " Runnable r = (Runnable & Serializable) (() -> {});" + EOL + + " r = (Runnable & Serializable)() -> {};" + EOL + + " r = (Runnable & I)() -> {};" + EOL + + " }}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0); + + assertEquals("Runnable r = (Runnable & Serializable) (() -> {" + EOL + "});", print(methodDeclaration.getBody().get().getStatements().get(0))); + } + + @Test + public void printIntersectionType() { + String code = "(Runnable & Serializable) (() -> {})"; + Expression expression = JavaParser.parseExpression(code); + Type type = ((CastExpr) expression).getType(); + + assertEquals("Runnable & Serializable", print(type)); + } + + @Test + public void printLambdaIntersectionTypeReturn() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + MethodDeclaration methodDeclaration = (MethodDeclaration) cu.getType(0).getMember(0); + + assertEquals("return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey());", print(methodDeclaration.getBody().get().getStatements().get(0))); + } + + @Test + public void printClassWithoutJavaDocButWithComment() { + String code = String.format("/** javadoc */ public class A { %s// stuff%s}", EOL, EOL); + CompilationUnit cu = JavaParser.parse(code); + PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavadoc(false); + String content = cu.toString(ignoreJavaDoc); + assertEquals(String.format("public class A {%s // stuff%s}%s", EOL, EOL, EOL), content); + } + + @Test + public void printImportsDefaultOrder() { + String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}"; + CompilationUnit cu = JavaParser.parse(code); + String content = cu.toString(); + assertEqualsNoEol("import x.y.z;\n" + + "import a.b.c;\n" + + "import static b.c.d;\n" + + "\n" + + "class c {\n" + + "}\n", content); + } + + @Test + public void printImportsOrdered() { + String code = "import x.y.z;import a.b.c;import static b.c.d;class c {}"; + CompilationUnit cu = JavaParser.parse(code); + PrettyPrinterConfiguration orderImports = new PrettyPrinterConfiguration().setOrderImports(true); + String content = cu.toString(orderImports); + assertEqualsNoEol("import static b.c.d;\n" + + "import a.b.c;\n" + + "import x.y.z;\n" + + "\n" + + "class c {\n" + + "}\n", content); + } + + @Test + public void multilineJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1\n line2 *\n * line3"); + + assertEqualsNoEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " * line2 *\n" + + " * line3\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + public void emptyJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment(""); + + assertEqualsNoEol("public class X {\n" + + "\n" + + " /**\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + public void multilineJavadocWithLotsOfEmptyLinesGetsFormattedNeatly() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("\n\n\n ab\n\n\n cd\n\n\n"); + + assertEqualsNoEol("public class X {\n" + + "\n" + + " /**\n" + + " * ab\n" + + " *\n" + + " * cd\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + public void singlelineJavadocGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setJavadocComment("line1"); + + assertEqualsNoEol("public class X {\n" + + "\n" + + " /**\n" + + " * line1\n" + + " */\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + public void singlelineCommentGetsFormatted() { + CompilationUnit cu = new CompilationUnit(); + cu.addClass("X").addMethod("abc").setComment(new LineComment(" line1 \n ")); + + assertEqualsNoEol("public class X {\n" + + "\n" + + " // line1\n" + + " void abc() {\n" + + " }\n" + + "}\n", cu.toString()); + } + + @Test + public void blockcommentGetsNoFormatting() { + CompilationUnit cu = JavaParser.parse("class A {\n" + + " public void helloWorld(String greeting, String name) {\n" + + " //sdfsdfsdf\n" + + " //sdfds\n" + + " /*\n" + + " dgfdgfdgfdgfdgfd\n" + + " */\n" + + " }\n" + + "}\n"); + + assertEqualsNoEol("class A {\n" + + "\n" + + " public void helloWorld(String greeting, String name) {\n" + + " // sdfsdfsdf\n" + + " // sdfds\n" + + " /*\n" + + " dgfdgfdgfdgfdgfd\n" + + " */\n" + + " }\n" + + "}\n", cu.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java new file mode 100644 index 000000000..fef360925 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/PrettyPrinterTest.java @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import static com.github.javaparser.JavaParser.*; +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static org.junit.Assert.assertEquals; + +public class PrettyPrinterTest { + + private String prettyPrintField(String code) { + CompilationUnit cu = parse(code); + return new PrettyPrinter().print(cu.findFirst(FieldDeclaration.class).get()); + } + + private String prettyPrintVar(String code) { + CompilationUnit cu = parse(code); + return new PrettyPrinter().print(cu.findAll(VariableDeclarationExpr.class).get(0)); + } + + @Test + public void printingArrayFields() { + String code; + code = "class A { int a, b[]; }"; + assertEquals("int a, b[];", prettyPrintField(code)); + + code = "class A { int[] a[], b[]; }"; + assertEquals("int[][] a, b;", prettyPrintField(code)); + + code = "class A { int[] a[][], b; }"; + assertEquals("int[] a[][], b;", prettyPrintField(code)); + + code = "class A { int[] a, b; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + + code = "class A { int a[], b[]; }"; + assertEquals("int[] a, b;", prettyPrintField(code)); + } + + @Test + public void printingArrayVariables() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("int a, b[]", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[], b[]; }}"; + assertEquals("int[][] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a[][], b; }}"; + assertEquals("int[] a[][], b", prettyPrintVar(code)); + + code = "class A { void foo(){ int[] a, b; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + + code = "class A { void foo(){ int a[], b[]; }}"; + assertEquals("int[] a, b", prettyPrintVar(code)); + } + + private String prettyPrintConfigurable(String code) { + CompilationUnit cu = parse(code); + PrettyPrinter printer = new PrettyPrinter(new PrettyPrinterConfiguration().setVisitorFactory(TestVisitor::new)); + return printer.print(cu.findFirst(ClassOrInterfaceDeclaration.class).get()); + } + + @Test + public void printUseTestVisitor() { + String code; + code = "class A { void foo(){ int a, b[]; }}"; + assertEquals("test", prettyPrintConfigurable(code)); + } + + @Test + public void prettyColumnAlignParameters_enabled() { + PrettyPrinterConfiguration config = new PrettyPrinterConfiguration() + .setIndent("\t") + .setColumnAlignParameters(true); + + final String EOL = config.getEndOfLineCharacter(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + "\tvoid foo(Object arg0, Object arg1) {" + EOL + + "\t\tmyMethod(1," + EOL + + "\t\t 2," + EOL + + "\t\t 3," + EOL + + "\t\t 5," + EOL + + "\t\t Object.class);" + EOL + + "\t}" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); + } + + @Test + public void prettyColumnAlignParameters_disabled() { + PrettyPrinterConfiguration config = new PrettyPrinterConfiguration(); + final String EOL = config.getEndOfLineCharacter(); + + String code = "class Example { void foo(Object arg0,Object arg1){ myMethod(1, 2, 3, 5, Object.class); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo(Object arg0, Object arg1) {" + EOL + + " myMethod(1, 2, 3, 5, Object.class);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); + } + + @Test + public void prettyAlignMethodCallChains_enabled() { + PrettyPrinterConfiguration config = new PrettyPrinterConfiguration() + .setIndent("\t") + .setColumnAlignFirstMethodChain(true); + + final String EOL = config.getEndOfLineCharacter(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + "\tvoid foo() {" + EOL + + "\t\tIntStream.range(0, 10)" + EOL + + "\t\t .filter(x -> x % 2 == 0)" + EOL + + "\t\t .map(x -> x * IntStream.of(1, 3, 5, 1)" + EOL + + "\t\t .sum())" + EOL + + "\t\t .forEach(System.out::println);" + EOL + + "\t}" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); + } + + @Test + public void prettyAlignMethodCallChains_disabled() { + PrettyPrinterConfiguration config = new PrettyPrinterConfiguration(); + final String EOL = config.getEndOfLineCharacter(); + + String code = "class Example { void foo() { IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1,3,5,1).sum()).forEach(System.out::println); } }"; + String expected = "class Example {" + EOL + + "" + EOL + + " void foo() {" + EOL + + " IntStream.range(0, 10).filter(x -> x % 2 == 0).map(x -> x * IntStream.of(1, 3, 5, 1).sum()).forEach(System.out::println);" + EOL + + " }" + EOL + + "}" + EOL + + ""; + + assertEquals(expected, new PrettyPrinter(config).print(parse(code))); + } + + @Test + public void enumConstantsHorizontally() { + CompilationUnit cu = parse("enum X{A, B, C, D, E}"); + assertEqualsNoEol("enum X {\n\n A, B, C, D, E\n}\n", new PrettyPrinter().print(cu)); + } + + @Test + public void enumConstantsVertically() { + CompilationUnit cu = parse("enum X{A, B, C, D, E, F}"); + assertEqualsNoEol("enum X {\n\n A,\n B,\n C,\n D,\n E,\n F\n}\n", new PrettyPrinter().print(cu)); + } + + @Test + public void printingInconsistentVariables() { + FieldDeclaration fieldDeclaration = parseBodyDeclaration("int a, b;").asFieldDeclaration(); + + assertEquals("int a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(0).setType(PrimitiveType.doubleType()); + + assertEquals("??? a, b;", fieldDeclaration.toString()); + + fieldDeclaration.getVariable(1).setType(PrimitiveType.doubleType()); + + assertEquals("double a, b;", fieldDeclaration.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java new file mode 100644 index 000000000..6cbe32808 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/TestVisitor.java @@ -0,0 +1,15 @@ +package com.github.javaparser.printer; + +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; + +public class TestVisitor extends PrettyPrintVisitor { + + public TestVisitor(PrettyPrinterConfiguration prettyPrinterConfiguration) { + super(prettyPrinterConfiguration); + } + + @Override + public void visit(final ClassOrInterfaceDeclaration n, final Void arg) { + printer.print("test"); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java new file mode 100644 index 000000000..b64989122 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/XmlPrinterTest.java @@ -0,0 +1,41 @@ +package com.github.javaparser.printer; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.expr.Expression; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class XmlPrinterTest { + @Test + public void testWithType() { + Expression expression = JavaParser.parseExpression("1+1"); + XmlPrinter xmlOutput = new XmlPrinter(true); + + String output = xmlOutput.output(expression); + + assertEquals("<root type='BinaryExpr' operator='PLUS'><left type='IntegerLiteralExpr' value='1'></left><right type='IntegerLiteralExpr' value='1'></right></root>", output); + } + + @Test + public void testWithoutType() { + Expression expression = JavaParser.parseExpression("1+1"); + + XmlPrinter xmlOutput = new XmlPrinter(false); + + String output = xmlOutput.output(expression); + + assertEquals("<root operator='PLUS'><left value='1'></left><right value='1'></right></root>", output); + } + + @Test + public void testList() { + Expression expression = JavaParser.parseExpression("a(1,2)"); + + XmlPrinter xmlOutput = new XmlPrinter(true); + + String output = xmlOutput.output(expression); + + assertEquals("<root type='MethodCallExpr'><name type='SimpleName' identifier='a'></name><arguments><argument type='IntegerLiteralExpr' value='1'></argument><argument type='IntegerLiteralExpr' value='2'></argument></arguments></root>", output); + } +}
\ No newline at end of file diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java new file mode 100644 index 000000000..435cd8198 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/YamlPrinterTest.java @@ -0,0 +1,94 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.printer;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.expr.Expression;
+
+public class YamlPrinterTest {
+
+ @Test
+ public void testWithType() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=MethodCallExpr): " + System.lineSeparator();
+ expectedOutput += " name(Type=SimpleName): " + System.lineSeparator();
+ expectedOutput += " identifier: \"x\"" + System.lineSeparator();
+ expectedOutput += " arguments: " + System.lineSeparator();
+ expectedOutput += " - argument(Type=IntegerLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += " - argument(Type=IntegerLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("x(1,1)");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithoutType() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root: " + System.lineSeparator();
+ expectedOutput += " operator: \"PLUS\"" + System.lineSeparator();
+ expectedOutput += " left: " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += " right: " + System.lineSeparator();
+ expectedOutput += " value: \"1\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(false);
+ Expression expression = JavaParser.parseExpression("1+1");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithColonFollowedBySpaceInValue() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=StringLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"a\\\\: b\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("\"a\\\\: b\"");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+
+ @Test
+ public void testWithColonFollowedByLineSeparatorInValue() {
+ String expectedOutput = "---" + System.lineSeparator();
+ expectedOutput += "root(Type=StringLiteralExpr): " + System.lineSeparator();
+ expectedOutput += " value: \"a\\\\:\\\\nb\"" + System.lineSeparator();
+ expectedOutput += "...";
+
+ YamlPrinter yamlPrinter = new YamlPrinter(true);
+ Expression expression = JavaParser.parseExpression("\"a\\\\:\\\\nb\"");
+ String output = yamlPrinter.output(expression);
+ assertEquals(expectedOutput, output);
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java new file mode 100644 index 000000000..108845772 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/AbstractLexicalPreservingTest.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.expr.Expression; +import org.junit.Before; + +import java.io.IOException; + +import static com.github.javaparser.utils.TestUtils.readResource; +import static org.junit.Assert.assertEquals; + +public abstract class AbstractLexicalPreservingTest { + + protected CompilationUnit cu; + protected Expression expression; + + protected void considerCode(String code) { + cu = LexicalPreservingPrinter.setup(JavaParser.parse(code)); + } + + protected void considerExpression(String code) { + expression = LexicalPreservingPrinter.setup(JavaParser.parseExpression(code)); + } + + protected String considerExample(String resourceName) throws IOException { + String code = readExample(resourceName); + considerCode(code); + return code; + } + + protected String readExample(String resourceName) throws IOException { + return readResource("com/github/javaparser/lexical_preservation_samples/" + resourceName + ".java.txt"); + } + + protected void assertTransformed(String exampleName, Node node) throws IOException { + String expectedCode = readExample(exampleName + "_expected"); + String actualCode = LexicalPreservingPrinter.print(node); + assertEquals(expectedCode, actualCode); + } + + protected void assertUnchanged(String exampleName) throws IOException { + String code = considerExample(exampleName + "_original"); + assertEquals(code, LexicalPreservingPrinter.print(cu != null ? cu : expression)); + } + + protected void assertTransformedToString(String expectedPartialCode, Node node) { + String actualCode = LexicalPreservingPrinter.print(node); + assertEquals(expectedPartialCode, actualCode); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java new file mode 100644 index 000000000..2fb98c1f5 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/DifferenceTest.java @@ -0,0 +1,428 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import com.github.javaparser.GeneratedJavaParserConstants; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmIndent; +import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; +import com.github.javaparser.printer.concretesyntaxmodel.CsmUnindent; +import com.github.javaparser.printer.lexicalpreservation.LexicalDifferenceCalculator.CsmChild; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; + +import static com.github.javaparser.TokenTypes.eolTokenKind; +import static com.github.javaparser.TokenTypes.spaceTokenKind; +import static com.github.javaparser.printer.lexicalpreservation.Difference.DifferenceElement.*; +import static org.junit.Assert.assertEquals; + +public class DifferenceTest extends AbstractLexicalPreservingTest { + + @Test + public void calculateDifferenceEmpty() { + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + Difference diff = Difference.calculate(a, b); + assertEquals(0, diff.getElements().size()); + } + + @Test + public void calculateDifferenceAIsEmpty() { + Node n1 = new FieldDeclaration(); + Node n2 = new MethodDeclaration(); + + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Arrays.asList( + new CsmToken(GeneratedJavaParserConstants.LPAREN), + new CsmChild(n1), + new CsmToken(GeneratedJavaParserConstants.RPAREN), + new CsmChild(n2))); + Difference diff = Difference.calculate(a, b); + assertEquals(4, diff.getElements().size()); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(0)); + assertEquals(added(new CsmChild(n1)), diff.getElements().get(1)); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(2)); + assertEquals(added(new CsmChild(n2)), diff.getElements().get(3)); + } + + @Test + public void calculateDifferenceBIsEmpty() { + Node n1 = new FieldDeclaration(); + Node n2 = new MethodDeclaration(); + + LexicalDifferenceCalculator.CalculatedSyntaxModel a = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Arrays.asList( + new CsmToken(GeneratedJavaParserConstants.LPAREN), + new CsmChild(n1), + new CsmToken(GeneratedJavaParserConstants.RPAREN), + new CsmChild(n2))); + LexicalDifferenceCalculator.CalculatedSyntaxModel b = new LexicalDifferenceCalculator.CalculatedSyntaxModel(Collections.emptyList()); + Difference diff = Difference.calculate(a, b); + assertEquals(4, diff.getElements().size()); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(0)); + assertEquals(removed(new CsmChild(n1)), diff.getElements().get(1)); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(2)); + assertEquals(removed(new CsmChild(n2)), diff.getElements().get(3)); + } + + @Test + public void compilationUnitExampleWithPackageSetDiff() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + PackageDeclaration packageDeclaration = new PackageDeclaration(new Name(new Name("foo"), "bar")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, cu); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, cu, ObservableProperty.PACKAGE_DECLARATION, null, packageDeclaration); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + assertEquals(3, diff.getElements().size()); + assertEquals(added(new CsmChild(packageDeclaration)), diff.getElements().get(0)); + assertEquals(kept(new CsmChild(cu.getType(0))), diff.getElements().get(1)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(2)); + } + + @Test + public void annotationDeclarationExampleWithModifierAdded() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC)); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + diff.removeIndentationElements(); + int i = 0; + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void annotationDeclarationExampleWithNameChanged() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + SimpleName newName = new SimpleName("NewName"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.NAME, + annotationDeclaration.getName(), newName); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + diff.removeIndentationElements(); + int i = 0; + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(removed(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++)); + assertEquals(added(new CsmChild(newName)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void annotationDeclarationExampleWithJavadocAdded() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + JavadocComment comment = new JavadocComment("Cool this annotation!"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, null, comment); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + diff.removeIndentationElements(); + int i = 0; + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void annotationDeclarationExampleWithJavadocRemoved() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, annotationDeclaration.getComment().get(), null); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + diff.removeIndentationElements(); + int i = 0; + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void annotationDeclarationExampleWithModifierRemoved() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, EnumSet.of(Modifier.PUBLIC), EnumSet.noneOf(Modifier.class)); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + diff.removeIndentationElements(); + int i = 0; + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.AT)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.INTERFACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(0))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(1))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(2))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(3))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(4))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(annotationDeclaration.getMember(5))), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void removeDefaultValueInAnnotationMemberDeclaration() { + AnnotationMemberDeclaration md = considerAmd("int foo() default 10;"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(md, ObservableProperty.DEFAULT_VALUE, md.getDefaultValue(), null); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(kept(new CsmChild(md.getType())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(md.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(removed(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), diff.getElements().get(i++)); + assertEquals(removed(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(removed(new CsmChild(md.getDefaultValue().get())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void addedDefaultValueInAnnotationMemberDeclaration() { + AnnotationMemberDeclaration md = considerAmd("int foo();"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + Expression defaultValue = new IntegerLiteralExpr(("10")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(md, ObservableProperty.DEFAULT_VALUE, null, defaultValue); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(kept(new CsmChild(md.getType())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(md.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(added(new CsmToken(GeneratedJavaParserConstants._DEFAULT)), diff.getElements().get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(added(new CsmChild(defaultValue)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.SEMICOLON)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void addedModifierToConstructorDeclaration() { + ConstructorDeclaration cd = considerCd("A(){}"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(cd); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(cd, ObservableProperty.MODIFIERS, + EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC)); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(added(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(added(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(cd.getName())), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++)); + assertEquals(kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(kept(new CsmChild(cd.getBody())), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void replacingNameForEnumConstantDeclaration() throws IOException { + EnumConstantDeclaration ecd = considerEcd("A"); + SimpleName newName = new SimpleName("B"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(ecd); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(ecd, ObservableProperty.NAME, + ecd.getName(), newName); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(Difference.DifferenceElement.removed(new CsmChild(ecd.getName())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmChild(newName)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void addingStatementToEmptyMethodBody() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + Statement s = new ExpressionStmt(new BinaryExpr( + new IntegerLiteralExpr("10"), new IntegerLiteralExpr("2"), BinaryExpr.Operator.PLUS + )); + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(m.getBody().get()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListAddition(m.getBody().get(), ObservableProperty.STATEMENTS, 0, s); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmIndent()), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmChild(s)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmToken(eolTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmUnindent()), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void methodDeclarationRemovingParameter() { + MethodDeclaration md = considerMd("public void foo(float f){}"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListRemoval(md, ObservableProperty.PARAMETERS, 0); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getType())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getName())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.removed(new CsmChild(md.getParameter(0))), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getBody().get())), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + @Test + public void methodDeclarationAddingParameter() { + MethodDeclaration md = considerMd("public void foo(){}"); + Parameter newParameter = new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(md); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterListAddition(md, ObservableProperty.PARAMETERS, 0, newParameter); + Difference diff = Difference.calculate(csmOriginal, csmChanged); + int i = 0; + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.PUBLIC)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getType())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getName())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.LPAREN)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.added(new CsmChild(newParameter)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(GeneratedJavaParserConstants.RPAREN)), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmToken(spaceTokenKind())), diff.getElements().get(i++)); + assertEquals(Difference.DifferenceElement.kept(new CsmChild(md.getBody().get())), diff.getElements().get(i++)); + assertEquals(i, diff.getElements().size()); + } + + private AnnotationMemberDeclaration considerAmd(String code) { + considerCode("@interface AD { " + code + " }"); + return (AnnotationMemberDeclaration)cu.getAnnotationDeclarationByName("AD").get().getMember(0); + } + + private ConstructorDeclaration considerCd(String code) { + considerCode("class A { " + code + " }"); + return (ConstructorDeclaration) cu.getType(0).getMembers().get(0); + } + + private EnumConstantDeclaration considerEcd(String code) { + considerCode("enum A { " + code + " }"); + return ((EnumDeclaration)cu.getType(0)).getEntries().get(0); + } + + private MethodDeclaration considerMd(String code) { + considerCode("class A { " + code + " }"); + return (MethodDeclaration) cu.getType(0).getMembers().get(0); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java new file mode 100644 index 000000000..d3e5490c0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalDifferenceCalculatorTest.java @@ -0,0 +1,300 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import com.github.javaparser.GeneratedJavaParserConstants; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.comments.JavadocComment; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.observer.ObservableProperty; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.printer.ConcreteSyntaxModel; +import com.github.javaparser.printer.concretesyntaxmodel.CsmElement; +import com.github.javaparser.printer.concretesyntaxmodel.CsmToken; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +import static com.github.javaparser.TokenTypes.eolTokenKind; +import static com.github.javaparser.TokenTypes.spaceTokenKind; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class LexicalDifferenceCalculatorTest extends AbstractLexicalPreservingTest { + + @Test + public void compilationUnitExampleOriginal() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmOriginal = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, cu); + assertEquals(2, csmOriginal.elements.size()); + assertEquals(new LexicalDifferenceCalculator.CsmChild(cu.getType(0)), csmOriginal.elements.get(0)); + assertEquals(new CsmToken(eolTokenKind()), csmOriginal.elements.get(1)); + } + + @Test + public void compilationUnitExampleWithPackageSet() { + considerCode("class A {}"); + CsmElement element = ConcreteSyntaxModel.forClass(cu.getClass()); + PackageDeclaration packageDeclaration = new PackageDeclaration(new Name(new Name("foo"), "bar")); + LexicalDifferenceCalculator.CalculatedSyntaxModel csmChanged = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, cu, ObservableProperty.PACKAGE_DECLARATION, null, packageDeclaration); + assertEquals(3, csmChanged.elements.size()); + assertEquals(new LexicalDifferenceCalculator.CsmChild(packageDeclaration), csmChanged.elements.get(0)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(cu.getType(0)), csmChanged.elements.get(1)); + assertEquals(new CsmToken(eolTokenKind()), csmChanged.elements.get(2)); + } + + @Test + public void annotationDeclarationModifiersExampleOriginal() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void annotationDeclarationModifiersExampleModified() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.MODIFIERS, EnumSet.noneOf(Modifier.class), EnumSet.of(Modifier.PUBLIC)); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.PUBLIC), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void annotationDeclarationNameExampleModified() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + SimpleName newName = new SimpleName("NewName"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.NAME, + annotationDeclaration.getName(), newName); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(newName), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void annotationDeclaratioJavadocExampleOriginal() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(element, annotationDeclaration); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.PUBLIC), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void annotationDeclaratioJavadocExampleAddingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + AnnotationDeclaration annotationDeclaration = (AnnotationDeclaration)cu.getType(0); + CsmElement element = ConcreteSyntaxModel.forClass(annotationDeclaration.getClass()); + JavadocComment comment = new JavadocComment("Cool this annotation!"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelAfterPropertyChange(element, annotationDeclaration, ObservableProperty.COMMENT, null, comment); + csm.removeIndentationElements(); + int i = 0; + assertEquals(new CsmToken(GeneratedJavaParserConstants.PUBLIC), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.AT), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.INTERFACE), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getName()), csm.elements.get(i++)); + assertEquals(new CsmToken(spaceTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.LBRACE), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(0)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(1)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(2)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(3)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(4)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new LexicalDifferenceCalculator.CsmChild(annotationDeclaration.getMember(5)), csm.elements.get(i++)); + assertEquals(new CsmToken(eolTokenKind()), csm.elements.get(i++)); + assertEquals(new CsmToken(GeneratedJavaParserConstants.RBRACE), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void simpleEnumConstantDeclaration() throws IOException { + EnumConstantDeclaration ecd = considerEcd("A"); + LexicalDifferenceCalculator.CalculatedSyntaxModel csm = new LexicalDifferenceCalculator().calculatedSyntaxModelForNode(ecd); + + int i = 0; + assertEquals(new LexicalDifferenceCalculator.CsmChild(ecd.getName()), csm.elements.get(i++)); + assertEquals(i, csm.elements.size()); + } + + @Test + public void csmModelAfterAddingStatementToEmptyBlock() throws IOException { + LexicalDifferenceCalculator ldc = new LexicalDifferenceCalculator(); + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + Statement assignStatement = new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + )); + LexicalDifferenceCalculator.CalculatedSyntaxModel calculatedSyntaxModel = + ldc.calculatedSyntaxModelAfterListAddition( + ConcreteSyntaxModel.forClass(BlockStmt.class), + ObservableProperty.STATEMENTS, + setter.getBody().get().getStatements(), + 0, + assignStatement); + int index = 0; + assertEquals(CsmElement.token(GeneratedJavaParserConstants.LBRACE), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.indent(), calculatedSyntaxModel.elements.get(index++)); + assertTrue(isChild(calculatedSyntaxModel.elements.get(index++), ExpressionStmt.class)); + assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.unindent(), calculatedSyntaxModel.elements.get(index++)); + assertEquals(CsmElement.token(GeneratedJavaParserConstants.RBRACE), calculatedSyntaxModel.elements.get(index++)); + assertEquals(index, calculatedSyntaxModel.elements.size()); + } + + @Test + public void differenceAfterddingStatementToEmptyBlock() throws IOException { + LexicalDifferenceCalculator ldc = new LexicalDifferenceCalculator(); + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + Statement assignStatement = new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + )); + Difference diff = ldc.calculateListAdditionDifference( + ObservableProperty.STATEMENTS, + setter.getBody().get().getStatements(), + 0, + assignStatement); + int index = 0; + assertEquals(Difference.DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.LBRACE)), diff.getElements().get(index++)); + assertEquals(Difference.DifferenceElement.kept(CsmElement.newline()), diff.getElements().get(index++)); + assertEquals(Difference.DifferenceElement.added(CsmElement.indent()), diff.getElements().get(index++)); + assertTrue(isAddedChild(diff.getElements().get(index++), ExpressionStmt.class)); + assertEquals(Difference.DifferenceElement.added(CsmElement.newline()), diff.getElements().get(index++)); + assertEquals(Difference.DifferenceElement.added(CsmElement.unindent()), diff.getElements().get(index++)); + assertEquals(Difference.DifferenceElement.kept(CsmElement.token(GeneratedJavaParserConstants.RBRACE)), diff.getElements().get(index++)); + assertEquals(index, diff.getElements().size()); + } + + private boolean isAddedChild(Difference.DifferenceElement element, Class<? extends Node> childClass) { + return element.isAdded() && isChild(element.getElement(), childClass); + } + + private boolean isChild(CsmElement element, Class<? extends Node> childClass) { + return element instanceof LexicalDifferenceCalculator.CsmChild && childClass.isInstance(((LexicalDifferenceCalculator.CsmChild)element).getChild()); + } + + protected EnumConstantDeclaration considerEcd(String code) { + considerCode("enum A { " + code + " }"); + return ((EnumDeclaration)cu.getType(0)).getEntries().get(0); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java new file mode 100644 index 000000000..796da14a2 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/LexicalPreservingPrinterTest.java @@ -0,0 +1,1051 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import com.github.javaparser.*; +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.*; +import com.github.javaparser.ast.type.Type; +import com.github.javaparser.ast.type.UnionType; +import com.github.javaparser.ast.type.VoidType; +import com.github.javaparser.ast.visitor.ModifierVisitor; +import com.github.javaparser.ast.visitor.Visitable; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.NODE_TEXT_DATA; +import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol; +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class LexicalPreservingPrinterTest extends AbstractLexicalPreservingTest { + private NodeText getTextForNode(Node node) { + return node.getData(NODE_TEXT_DATA); + } + + + // + // Tests on TextNode definition + // + + @Test + public void checkNodeTextCreatedForSimplestClass() { + considerCode("class A {}"); + + // CU + assertEquals(1, getTextForNode(cu).numberOfElements()); + assertEquals(true, getTextForNode(cu).getTextElement(0) instanceof ChildTextElement); + assertEquals(cu.getClassByName("A").get(), ((ChildTextElement)getTextForNode(cu).getTextElement(0)).getChild()); + + // Class + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + assertEquals(7, getTextForNode(classA).numberOfElements()); + assertEquals("class", getTextForNode(classA).getTextElement(0).expand()); + assertEquals(" ", getTextForNode(classA).getTextElement(1).expand()); + assertEquals("A", getTextForNode(classA).getTextElement(2).expand()); + assertEquals(" ", getTextForNode(classA).getTextElement(3).expand()); + assertEquals("{", getTextForNode(classA).getTextElement(4).expand()); + assertEquals("}", getTextForNode(classA).getTextElement(5).expand()); + assertEquals("", getTextForNode(classA).getTextElement(6).expand()); + assertEquals(true, getTextForNode(classA).getTextElement(6) instanceof TokenTextElement); + assertEquals(GeneratedJavaParserConstants.EOF, ((TokenTextElement)getTextForNode(classA).getTextElement(6)).getTokenKind()); + } + + @Test + public void checkNodeTextCreatedForField() { + String code = "class A {int i;}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + FieldDeclaration fd = classA.getFieldByName("i").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(fd); + assertEquals(Arrays.asList("int", " ", "i", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedForVariableDeclarator() { + String code = "class A {int i;}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + FieldDeclaration fd = classA.getFieldByName("i").get(); + VariableDeclarator vd = fd.getVariables().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(vd); + assertEquals(Arrays.asList("i"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedForMethod() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("void", " ", "foo", "(", "int p1", ",", " ", "float p2", ")", " ", "{ }"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedForMethodParameter() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + Parameter p1 = md.getParameterByName("p1").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(p1); + assertEquals(Arrays.asList("int", " ", "p1"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedForPrimitiveType() { + String code = "class A {void foo(int p1, float p2) { }}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + MethodDeclaration md = classA.getMethodsByName("foo").get(0); + Parameter p1 = md.getParameterByName("p1").get(); + Type t = p1.getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(t); + assertEquals(Arrays.asList("int"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedForSimpleImport() { + String code = "import a.b.c.D;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(imp); + assertEquals(Arrays.asList("import", " ", "a.b.c.D", ";", ""), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedGenericType() { + String code = "class A {ParseResult<T> result;}"; + considerCode(code); + + FieldDeclaration field = cu.getClassByName("A").get().getFieldByName("result").get(); + Node t = field.getCommonType(); + Node t2 = field.getVariable(0).getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(field); + assertEquals(Arrays.asList("ParseResult", "<", "T", ">", " ", "result", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedAnnotationDeclaration() { + String code = "public @interface ClassPreamble { String author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(ad); + assertEquals(Arrays.asList("public", " ", "@", "interface", " ", "ClassPreamble", " ", "{", " ", "String author();", " ", "}", ""), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedAnnotationMemberDeclaration() { + String code = "public @interface ClassPreamble { String author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String", " ", "author", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedAnnotationMemberDeclarationWithArrayType() { + String code = "public @interface ClassPreamble { String[] author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String[]", " ", "author", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedAnnotationMemberDeclarationArrayType() { + String code = "public @interface ClassPreamble { String[] author(); }"; + considerCode(code); + + AnnotationDeclaration ad = cu.getAnnotationDeclarationByName("ClassPreamble").get(); + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)ad.getMember(0).asAnnotationMemberDeclaration(); + Type type = md.getType(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(type); + assertEquals(Arrays.asList("String", "[", "]"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedAnnotationMemberDeclarationWithComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + + AnnotationMemberDeclaration md = (AnnotationMemberDeclaration)cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5).asAnnotationMemberDeclaration(); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(md); + assertEquals(Arrays.asList("String[]", " ", "reviewers", "(", ")", ";"), + nodeText.getElements().stream().map(TextElement::expand).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedArrayCreationLevelWithoutExpression() throws IOException { + considerExpression("new int[]"); + + ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)expression.asArrayCreationExpr(); + ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); + assertEquals(Arrays.asList("[", "]"), + nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()).collect(Collectors.toList())); + } + + @Test + public void checkNodeTextCreatedArrayCreationLevelWith() throws IOException { + considerExpression("new int[123]"); + + ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)expression.asArrayCreationExpr(); + ArrayCreationLevel arrayCreationLevel = arrayCreationExpr.getLevels().get(0); + NodeText nodeText = LexicalPreservingPrinter.getOrCreateNodeText(arrayCreationLevel); + assertEquals(Arrays.asList("[", "123", "]"), + nodeText.getElements().stream().map(TextElement::expand).filter(e -> !e.isEmpty()).collect(Collectors.toList())); + } + + // + // Tests on findIndentation + // + + @Test + public void findIndentationForAnnotationMemberDeclarationWithoutComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(4); + List<TokenTextElement> indentation = LexicalPreservingPrinter.findIndentation(node); + assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList())); + } + + @Test + public void findIndentationForAnnotationMemberDeclarationWithComment() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + Node node = cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(5); + List<TokenTextElement> indentation = LexicalPreservingPrinter.findIndentation(node); + assertEquals(Arrays.asList(" ", " ", " "), indentation.stream().map(TokenTextElement::expand).collect(Collectors.toList())); + } + + // + // Tests on printing + // + + @Test + public void printASuperSimpleCUWithoutChanges() { + String code = "class A {}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printASuperSimpleClassWithAFieldAdded() { + String code = "class A {}"; + considerCode(code); + + ClassOrInterfaceDeclaration classA = cu.getClassByName("A").get(); + classA.addField("int", "myField"); + assertEquals("class A {" + EOL + " int myField;"+EOL+"}", LexicalPreservingPrinter.print(classA)); + } + + @Test + public void printASuperSimpleClassWithoutChanges() { + String code = "class A {}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); + } + + @Test + public void printASimpleCUWithoutChanges() { + String code = "class /*a comment*/ A {\t\t"+EOL+" int f;"+EOL+EOL+EOL+" void foo(int p ) { return 'z' \t; }}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + assertEquals(code, LexicalPreservingPrinter.print(cu.getClassByName("A").get())); + assertEquals("void foo(int p ) { return 'z' \t; }", LexicalPreservingPrinter.print(cu.getClassByName("A").get().getMethodsByName("foo").get(0))); + } + + @Test + public void printASimpleClassRemovingAField() { + String code = "class /*a comment*/ A {\t\t"+EOL+" int f;"+EOL+EOL+EOL+" void foo(int p ) { return 'z' \t; }}"; + considerCode(code); + + ClassOrInterfaceDeclaration c = cu.getClassByName("A").get(); + c.getMembers().remove(0); + assertEquals("class /*a comment*/ A {\t\t"+ EOL + + EOL + + " void foo(int p ) { return 'z' \t; }}", LexicalPreservingPrinter.print(c)); + } + + @Test + public void printASimpleMethodAddingAParameterToAMethodWithZeroParameters() { + String code = "class A { void foo() {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.addParameter("float", "p1"); + assertEquals("void foo(float p1) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleMethodAddingAParameterToAMethodWithOneParameter() { + String code = "class A { void foo(char p1) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.addParameter("float", "p2"); + assertEquals("void foo(char p1, float p2) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleMethodRemovingAParameterToAMethodWithOneParameter() { + String code = "class A { void foo(float p1) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(0); + assertEquals("void foo() {}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleMethodRemovingParameterOneFromMethodWithTwoParameters() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(0); + assertEquals("void foo(int p2) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleMethodRemovingParameterTwoFromMethodWithTwoParameters() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + m.getParameters().remove(1); + assertEquals("void foo(char p1) {}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleMethodAddingAStatement() { + String code = "class A { void foo(char p1, int p2) {} }"; + considerCode(code); + + Statement s = new ExpressionStmt(new BinaryExpr( + new IntegerLiteralExpr("10"), new IntegerLiteralExpr("2"), BinaryExpr.Operator.PLUS + )); + NodeList<Statement> stmts = cu.getClassByName("A").get().getMethodsByName("foo").get(0).getBody().get().getStatements(); + stmts.add(s); + MethodDeclaration m = cu.getClassByName("A").get().getMethodsByName("foo").get(0); + assertEquals("void foo(char p1, int p2) {"+EOL + + " 10 + 2;"+ EOL + + "}", LexicalPreservingPrinter.print(m)); + } + + @Test + public void printASimpleImport() { + String code = "import a.b.c.D;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); + assertEquals("import a.b.c.D;", LexicalPreservingPrinter.print(imp)); + } + + @Test + public void printAnotherImport() { + String code = "import com.github.javaparser.ast.CompilationUnit;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); + assertEquals("import com.github.javaparser.ast.CompilationUnit;", LexicalPreservingPrinter.print(imp)); + } + + @Test + public void printAStaticImport() { + String code = "import static com.github.javaparser.ParseStart.*;"; + considerCode(code); + + ImportDeclaration imp = (ImportDeclaration)cu.getChildNodes().get(0); + assertEquals("import static com.github.javaparser.ParseStart.*;", LexicalPreservingPrinter.print(imp)); + } + + @Test + public void checkAnnidatedTypeParametersPrinting() { + String code = "class A { private final Stack<Iterator<Triple>> its = new Stack<Iterator<Triple>>(); }"; + considerCode(code); + assertEquals("class A { private final Stack<Iterator<Triple>> its = new Stack<Iterator<Triple>>(); }", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printASingleCatch() { + String code = "class A {{try { doit(); } catch (Exception e) {}}}"; + considerCode(code); + + assertEquals("class A {{try { doit(); } catch (Exception e) {}}}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printAMultiCatch() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + + assertEquals("class A {{try { doit(); } catch (Exception | AssertionError e) {}}}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printASingleCatchType() { + String code = "class A {{try { doit(); } catch (Exception e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration)cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt)initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + Type catchType = catchClause.getParameter().getType(); + + assertEquals("Exception", LexicalPreservingPrinter.print(catchType)); + } + + @Test + public void printUnionType() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration)cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt)initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + UnionType unionType = (UnionType)catchClause.getParameter().getType(); + + assertEquals("Exception | AssertionError", LexicalPreservingPrinter.print(unionType)); + } + + @Test + public void printParameterHavingUnionType() { + String code = "class A {{try { doit(); } catch (Exception | AssertionError e) {}}}"; + considerCode(code); + InitializerDeclaration initializerDeclaration = (InitializerDeclaration)cu.getType(0).getMembers().get(0); + TryStmt tryStmt = (TryStmt)initializerDeclaration.getBody().getStatements().get(0); + CatchClause catchClause = tryStmt.getCatchClauses().get(0); + Parameter parameter = catchClause.getParameter(); + + assertEquals("Exception | AssertionError e", LexicalPreservingPrinter.print(parameter)); + } + + @Test + public void printLambaWithUntypedParams() { + String code = "class A {Function<String,String> f = a -> a;}"; + considerCode(code); + + assertEquals("class A {Function<String,String> f = a -> a;}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printAModuleInfoSpecificKeywordUsedAsIdentifier1() { + considerCode("class module { }"); + + cu.getClassByName("module").get().setName("xyz"); + + assertEquals("class xyz { }", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printAModuleInfoSpecificKeywordUsedAsIdentifier2() { + considerCode("class xyz { }"); + + cu.getClassByName("xyz").get().setName("module"); + + assertEquals("class module { }", LexicalPreservingPrinter.print(cu)); + } + + // Issue 823: setPackageDeclaration on CU starting with a comment + @Test + public void reactToSetPackageDeclarationOnCuStartingWithComment() { + considerCode("// Hey, this is a comment\n" + + "\n" + + "\n" + + "// Another one\n" + + "\n" + + "class A {}"); + cu.setPackageDeclaration("org.javaparser.lexicalpreservation.examples"); + } + + @Test + public void printLambdaIntersectionTypeAssignment() { + String code = "class A {" + EOL + + " void f() {" + EOL + + " Runnable r = (Runnable & Serializable) (() -> {});" + EOL + + " r = (Runnable & Serializable)() -> {};" + EOL + + " r = (Runnable & I)() -> {};" + EOL + + " }}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + @Test + public void printLambdaIntersectionTypeReturn() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + considerCode(code); + + assertEquals(code, LexicalPreservingPrinter.print(cu)); + } + + // See issue #855 + @Test + public void handleOverrideAnnotation() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (!methodDeclaration.getAnnotationByName("Override").isPresent()) { + methodDeclaration.addAnnotation("Override"); + } + } + })); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " @Override()" + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void preserveSpaceAsIsForASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + assertEquals(readExample("ASimpleClassWithMoreFormatting"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void renameASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step1"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void theLexicalPreservationStringForAnAddedMethodShouldBeIndented() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", Modifier.PUBLIC); + assertEquals("public void setAField() {" + EOL + + " }", LexicalPreservingPrinter.print(setter)); + } + + @Test + public void addMethodToASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", Modifier.PUBLIC); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step2"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void addingParameterToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", Modifier.PUBLIC); + setter.addParameter("boolean", "aField"); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step3"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void findIndentationOfEmptyMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); + } + + @Test + public void findIndentationOfMethodWithStatements() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step4"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter).size()); + assertEquals(4, LexicalPreservingPrinter.findIndentation(setter.getBody().get()).size()); + assertEquals(8, LexicalPreservingPrinter.findIndentation(setter.getBody().get().getStatement(0)).size()); + } + + @Test + public void addingStatementToAnAddedMethodInASimpleClassWithMoreFormatting() throws IOException { + considerExample("ASimpleClassWithMoreFormatting"); + + cu.getClassByName("ASimpleClass").get() + .setName("MyRenamedClass"); + MethodDeclaration setter = cu + .getClassByName("MyRenamedClass").get() + .addMethod("setAField", Modifier.PUBLIC); + setter.addParameter("boolean", "aField"); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + ))); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void addingStatementToAnAddedMethodInASimpleClassWithMoreFormattingFromStep3() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + ))); + assertEquals(readExample("ASimpleClassWithMoreFormatting_step4"), LexicalPreservingPrinter.print(cu)); + } + + @Test + public void nodeTextForMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step4"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + NodeText nodeText; + + nodeText = getTextForNode(setter); + int index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.PUBLIC)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(VoidType.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(SimpleName.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LPAREN)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Parameter.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RPAREN)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(BlockStmt.class)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get()); + index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LBRACE)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(ExpressionStmt.class)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RBRACE)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get().getStatement(0)); + index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(AssignExpr.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SEMICOLON)); + assertEquals(index, nodeText.getElements().size()); + } + + @Test + public void nodeTextForModifiedMethod() throws IOException { + considerExample("ASimpleClassWithMoreFormatting_step3"); + + MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get() + .getMethodsByName("setAField").get(0); + setter.getBody().get().getStatements().add(new ExpressionStmt( + new AssignExpr( + new FieldAccessExpr(new ThisExpr(),"aField"), + new NameExpr("aField"), + AssignExpr.Operator.ASSIGN + ))); + NodeText nodeText; + + nodeText = getTextForNode(setter); + int index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.PUBLIC)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(VoidType.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(SimpleName.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LPAREN)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(Parameter.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RPAREN)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(BlockStmt.class)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = getTextForNode(setter.getBody().get()); + index = 0; + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.LBRACE)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isChildOfClass(ExpressionStmt.class)); + assertTrue(nodeText.getElements().get(index++).isNewline()); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SPACE)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.RBRACE)); + assertEquals(index, nodeText.getElements().size()); + + nodeText = LexicalPreservingPrinter.getOrCreateNodeText(setter.getBody().get().getStatement(0)); + index = 0; + assertTrue(nodeText.getElements().get(index++).isChildOfClass(AssignExpr.class)); + assertTrue(nodeText.getElements().get(index++).isToken(GeneratedJavaParserConstants.SEMICOLON)); + assertEquals(index, nodeText.getElements().size()); + } + + // See issue #926 + @Test + public void addASecondStatementToExistingMethod() throws IOException { + considerExample("MethodWithOneStatement"); + + MethodDeclaration methodDeclaration = cu.getType(0).getMethodsByName("someMethod").get(0); + methodDeclaration.getBody().get().getStatements().add(new ExpressionStmt( + new VariableDeclarationExpr( + new VariableDeclarator( + JavaParser.parseClassOrInterfaceType("String"), + "test2", + new StringLiteralExpr(""))) + )); + assertEquals("public void someMethod() {" + EOL + + " String test = \"\";" + EOL + + " String test2 = \"\";" + EOL + + " }", LexicalPreservingPrinter.print(methodDeclaration)); + } + + // See issue #866 + @Test + public void moveOverrideAnnotations() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " protected @Override void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> { + type.getMembers() + .forEach(member -> { + member.ifMethodDeclaration(methodDeclaration -> { + if (methodDeclaration.getAnnotationByName("Override").isPresent()) { + + while (methodDeclaration.getAnnotations().isNonEmpty()) { + AnnotationExpr annotationExpr = methodDeclaration.getAnnotations().get(0); + annotationExpr.remove(); + } + + methodDeclaration.addMarkerAnnotation("Override"); + } + }); + }); + }); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #866 + @Test + public void moveOrAddOverrideAnnotations() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " protected @Override void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> { + type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (methodDeclaration.getAnnotationByName("Override").isPresent()) { + + while (methodDeclaration.getAnnotations().isNonEmpty()) { + AnnotationExpr annotationExpr = methodDeclaration.getAnnotations().get(0); + annotationExpr.remove(); + } + } + methodDeclaration.addMarkerAnnotation("Override"); + } + }); + }); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " @Override" + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + public void handleAddingMarkerAnnotation() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> { + type.getMembers() + .forEach(member -> { + if (member instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) member; + if (!methodDeclaration.getAnnotationByName("Override").isPresent()) { + methodDeclaration.addMarkerAnnotation("Override"); + } + } + }); + }); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " @Override" + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + public void handleOverrideMarkerAnnotation() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " protected void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> + member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addMarkerAnnotation("Override") + ))); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " @Override" + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + // See issue #865 + @Test + public void handleOverrideAnnotationAlternative() { + String code = "public class TestPage extends Page {" + EOL + + EOL + + " protected void test() {}" + EOL + + EOL + + " protected void initializePage() {}" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes() + .forEach(type -> type.getMembers() + .forEach(member -> member.ifMethodDeclaration(methodDeclaration -> methodDeclaration.addAnnotation("Override")))); + assertEquals("public class TestPage extends Page {" + EOL + + EOL + + " @Override()" + EOL + + " protected void test() {}" + EOL + + EOL + + " @Override()" + EOL + + " protected void initializePage() {}" + EOL + + "}", LexicalPreservingPrinter.print(cu)); + } + + @Test + public void invokeModifierVisitor() { + String code = "class A {" + EOL + + " Object f() {" + EOL + + " return (Comparator<Map.Entry<K, V>> & Serializable)(c1, c2) -> c1.getKey().compareTo(c2.getKey()); " + EOL + + "}}"; + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + cu.accept(new ModifierVisitor<>(), null); + } + + @Test + public void handleDeprecatedAnnotationFinalClass() { + String code = "public final class A {}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); + + assertEquals("@Deprecated()" + EOL + + "public final class A {}" , LexicalPreservingPrinter.print(cu)); + + } + + @Test + public void handleDeprecatedAnnotationAbstractClass() { + String code = "public abstract class A {}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + + cu.getTypes().forEach(type -> type.addAndGetAnnotation(Deprecated.class)); + + assertEquals("@Deprecated()" + EOL + + "public abstract class A {}" , LexicalPreservingPrinter.print(cu)); + } + + @Test + public void issue1244() { + String code = "public class Foo {" + EOL + EOL + + "// Some comment" + EOL + EOL // does work with only one \n + + "public void writeExternal() {}" + EOL + "}"; + CompilationUnit originalCu = JavaParser.parse(code); + CompilationUnit cu = LexicalPreservingPrinter.setup(originalCu); + + cu.findAll(ClassOrInterfaceDeclaration.class).stream().forEach(c -> { + List<MethodDeclaration> methods = c.getMethodsByName("writeExternal"); + for (MethodDeclaration method : methods) { + c.remove(method); + } + }); + assertEqualsNoEol("public class Foo {\n" + + "// Some comment\n\n" + + "}", LexicalPreservingPrinter.print(cu)); + } + + static class AddFooCallModifierVisitor extends ModifierVisitor<Void> { + @Override + public Visitable visit(MethodCallExpr n, Void arg) { + // Add a call to foo() on every found method call + return new MethodCallExpr(n, "foo"); + } + } + + // See issue 1277 + @Test + public void testInvokeModifierVisitor() throws IOException { + String code = "class A {" + EOL + + " public String message = \"hello\";" + EOL + + " void bar() {" + EOL + + " System.out.println(\"hello\");" + EOL + + " }" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + cu.accept(new AddFooCallModifierVisitor(), null); + } + + static class CallModifierVisitor extends ModifierVisitor<Void> { + @Override + public Visitable visit(MethodCallExpr n, Void arg) { + // Add a call to foo() on every found method call + return new MethodCallExpr(n.clone(), "foo"); + } + } + + @Test + public void invokeModifierVisitorIssue1297() { + String code = "class A {" + EOL + + " public void bar() {" + EOL + + " System.out.println(\"hello\");" + EOL + + " System.out.println(\"hello\");" + EOL + + " // comment" + EOL + + " }" + EOL + + "}"; + + CompilationUnit cu = JavaParser.parse(code); + LexicalPreservingPrinter.setup(cu); + cu.accept(new CallModifierVisitor(), null); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java new file mode 100644 index 000000000..ec89dd1ff --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/TransformationsTest.java @@ -0,0 +1,143 @@ +package com.github.javaparser.printer.lexicalpreservation; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.NullLiteralExpr; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +/** + * These tests are more "high level" than the ones in LexicalPreservingPrinterTest. + * The idea is to perform some transformations on the code, print it back and see if the generated code + * is the expected one. We do not care about the internal state of LexicalPreservingPrinter, just the visible result. + */ +public class TransformationsTest extends AbstractLexicalPreservingTest { + + @Test + public void unchangedSimpleClasses() throws IOException { + assertUnchanged("Example1"); + assertUnchanged("Example2"); + } + + @Test + public void unchangedComplexFile() throws IOException { + assertUnchanged("Example4"); + } + + @Test + public void example1() throws IOException { + considerExample("Example1_original"); + cu.getClassByName("A").get().getFieldByName("a").get().setModifiers(EnumSet.of(Modifier.STATIC)); + assertTransformed("Example1", cu); + } + + @Test + public void example2() throws IOException { + considerExample("Example2_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer("10"); + assertTransformed("Example2", cu); + } + + @Test + public void example3() throws IOException { + considerExample("Example3_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer((Expression) null); + assertTransformed("Example3", cu); + } + + @Test + public void example5() throws IOException { + considerExample("Example5_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer(new NullLiteralExpr()); + assertTransformed("Example5", cu); + } + + @Test + public void example6() throws IOException { + considerExample("Example6_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setName("someOtherName"); + assertTransformed("Example6", cu); + } + + @Test + public void example7() throws IOException { + considerExample("Example7_original"); + cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setType(new ArrayType(PrimitiveType.intType())); + assertTransformed("Example7", cu); + } + + @Test + public void example8() throws IOException { + considerExample("Example8_original"); + FieldDeclaration fd = (FieldDeclaration) cu.getClassByName("A").get().getMember(0).asFieldDeclaration(); + fd.addVariable(new VariableDeclarator(PrimitiveType.intType(), "b")); + assertTransformed("Example8", cu); + } + + @Test + public void example9() throws IOException { + considerExample("Example9_original"); + FieldDeclaration fd = (FieldDeclaration) cu.getClassByName("A").get().getMember(0).asFieldDeclaration(); + fd.addVariable(new VariableDeclarator(new ArrayType(PrimitiveType.intType()), "b")); + assertTransformed("Example9", cu); + } + + @Test + public void example10() throws IOException { + considerExample("Example10_original"); + cu.getClassByName("A").get().getMembers().remove(0); + assertTransformed("Example10", cu); + } + + @Test + public void exampleParam1() throws IOException { + considerExample("Example_param1_original"); + MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.addParameter("int", "p1"); + assertTransformed("Example_param1", cu); + } + + @Test + public void exampleParam2() throws IOException { + considerExample("Example_param1_original"); + MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.addParameter(new ArrayType(PrimitiveType.intType()), "p1"); + md.addParameter("char", "p2"); + assertTransformed("Example_param2", cu); + } + + @Test + public void exampleParam3() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.getParameters().remove(0); + assertTransformed("Example_param3", cu); + } + + @Test + public void exampleParam4() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.getParameters().remove(1); + assertTransformed("Example_param4", cu); + } + + @Test + public void exampleParam5() throws IOException { + considerExample("Example_param3_original"); + MethodDeclaration md = (MethodDeclaration) cu.getClassByName("A").get().getMember(0).asMethodDeclaration(); + md.setType(PrimitiveType.intType()); + assertTransformed("Example_param5b", cu); + md.getBody().get().getStatements().add(new ReturnStmt(new NameExpr("p1"))); + assertTransformed("Example_param5", cu); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java new file mode 100644 index 000000000..93cff347e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/ArrayCreationLevelTransformationsTest.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast; + +import com.github.javaparser.ast.ArrayCreationLevel; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.expr.ArrayCreationExpr; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import com.github.javaparser.utils.Utils; +import org.junit.Test; + +import java.io.IOException; + +/** + * Transforming ArrayCreationLevel and verifying the LexicalPreservation works as expected. + */ +public class ArrayCreationLevelTransformationsTest extends AbstractLexicalPreservingTest { + + protected ArrayCreationLevel consider(String code) { + considerExpression("new int" + code); + ArrayCreationExpr arrayCreationExpr = expression.asArrayCreationExpr(); + return arrayCreationExpr.getLevels().get(0); + } + + // Dimension + + @Test + public void addingDimension() throws IOException { + ArrayCreationLevel it = consider("[]"); + it.setDimension(new IntegerLiteralExpr("10")); + assertTransformedToString("[10]", it); + } + + @Test + public void removingDimension() throws IOException { + ArrayCreationLevel it = consider("[10]"); + it.removeDimension(); + assertTransformedToString("[]", it); + } + + @Test + public void replacingDimension() throws IOException { + ArrayCreationLevel it = consider("[10]"); + it.setDimension(new IntegerLiteralExpr("12")); + assertTransformedToString("[12]", it); + } + + // Annotations + + @Test + public void addingAnnotation() throws IOException { + ArrayCreationLevel it = consider("[]"); + it.addAnnotation("myAnno"); + assertTransformedToString("@myAnno()"+ Utils.EOL+"[]", it); + } + + @Test + public void removingAnnotation() throws IOException { + ArrayCreationLevel it = consider("@myAnno []"); + it.getAnnotations().remove(0); + assertTransformedToString("[]", it); + } + + @Test + public void replacingAnnotation() throws IOException { + ArrayCreationLevel it = consider("@myAnno []"); + it.getAnnotations().set(0, new NormalAnnotationExpr(new Name("myOtherAnno"), new NodeList<>())); + assertTransformedToString("@myOtherAnno() []", it); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java new file mode 100644 index 000000000..304037829 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/CompilationUnitTransformationsTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast; + +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; + +import static com.github.javaparser.utils.Utils.EOL; + +/** + * Transforming CompilationUnit and verifying the LexicalPreservation works as expected. + */ +public class CompilationUnitTransformationsTest extends AbstractLexicalPreservingTest { + + // packageDeclaration + + @Test + public void addingPackageDeclaration() throws IOException { + considerCode("class A {}"); + cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo"), "bar"))); + assertTransformedToString("package foo.bar;"+ EOL + EOL + "class A {}", cu); + } + + @Test + public void removingPackageDeclaration() throws IOException { + considerCode("package foo.bar; class A {}"); + cu.removePackageDeclaration(); + assertTransformedToString("class A {}", cu); + } + + @Test + public void replacingPackageDeclaration() throws IOException { + considerCode("package foo.bar; class A {}"); + cu.setPackageDeclaration(new PackageDeclaration(new Name(new Name("foo2"), "baz"))); + assertTransformedToString("package foo2.baz;" + + EOL + EOL + + " class A {}", cu); + } + + // imports + + // types +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java new file mode 100644 index 000000000..a2ffd40a1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationDeclarationTransformationsTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +import static org.junit.Assert.assertEquals; + +/** + * Transforming AnnotationDeclaration and verifying the LexicalPreservation works as expected. + */ +public class AnnotationDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + @Test + public void unchangedExamples() throws IOException { + assertUnchanged("AnnotationDeclaration_Example1"); + assertUnchanged("AnnotationDeclaration_Example3"); + assertUnchanged("AnnotationDeclaration_Example9"); + } + + // name + + @Test + public void changingName() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setName("NewName"); + assertTransformed("AnnotationDeclaration_Example1", cu); + } + + // modifiers + + @Test + public void addingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example1_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformed("AnnotationDeclaration_Example2", cu); + } + + @Test + public void removingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformed("AnnotationDeclaration_Example3", cu); + } + + @Test + public void replacingModifiers() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformed("AnnotationDeclaration_Example4", cu); + } + + // members + + @Test + public void addingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().addMember(new AnnotationMemberDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), "foo", null)); + assertTransformed("AnnotationDeclaration_Example5", cu); + } + + @Test + public void removingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().getMember(2).remove(); + assertTransformed("AnnotationDeclaration_Example6", cu); + } + + @Test + public void replacingMember() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setMember(2, new AnnotationMemberDeclaration(EnumSet.noneOf(Modifier.class), PrimitiveType.intType(), "foo", null)); + assertTransformed("AnnotationDeclaration_Example7", cu); + } + + // javadoc + + @Test + public void addingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example3_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setJavadocComment("Cool this annotation!"); + assertTransformed("AnnotationDeclaration_Example8", cu); + } + + @Test + public void removingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + boolean removed = cu.getAnnotationDeclarationByName("ClassPreamble").get().getJavadocComment().get().remove(); + assertEquals(true, removed); + assertTransformed("AnnotationDeclaration_Example9", cu); + } + + @Test + public void replacingJavadoc() throws IOException { + considerExample("AnnotationDeclaration_Example9_original"); + cu.getAnnotationDeclarationByName("ClassPreamble").get().setJavadocComment("Super extra cool this annotation!!!"); + assertTransformed("AnnotationDeclaration_Example10", cu); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java new file mode 100644 index 000000000..6b5552807 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/AnnotationMemberDeclarationTransformationsTest.java @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.util.EnumSet; + +import static com.github.javaparser.utils.Utils.EOL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Transforming AnnotationMemberDeclaration and verifying the LexicalPreservation works as expected. + */ +public class AnnotationMemberDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected AnnotationMemberDeclaration consider(String code) { + considerCode("@interface AD { " + code + " }"); + return cu.getAnnotationDeclarationByName("AD").get().getMember(0).asAnnotationMemberDeclaration(); + } + + // Name + + @Test + public void changingName() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setName("bar"); + assertTransformedToString("int bar();", md); + } + + // Type + + @Test + public void changingType() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setType("String"); + assertTransformedToString("String foo();", md); + } + + // Modifiers + + @Test + public void addingModifiers() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public int foo();", md); + } + + @Test + public void removingModifiers() { + AnnotationMemberDeclaration md = consider("public int foo();"); + md.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("int foo();", md); + } + + @Test + public void replacingModifiers() { + AnnotationMemberDeclaration md = consider("public int foo();"); + md.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected int foo();", md); + } + + // Default value + + @Test + public void addingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo();"); + md.setDefaultValue(new IntegerLiteralExpr("10")); + assertTransformedToString("int foo() default 10;", md); + } + + @Test + public void removingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo() default 10;"); + assertEquals(true, md.getDefaultValue().get().remove()); + assertTransformedToString("int foo();", md); + } + + @Test + public void replacingDefaultValue() { + AnnotationMemberDeclaration md = consider("int foo() default 10;"); + md.setDefaultValue(new IntegerLiteralExpr("11")); + assertTransformedToString("int foo() default 11;", md); + } + + // Annotations + + @Test + public void addingAnnotation() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.addAnnotation("myAnno"); + assertTransformedToString("@myAnno()" + EOL + "int foo();", it); + } + + @Test + public void addingTwoAnnotations() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.addAnnotation("myAnno"); + it.addAnnotation("myAnno2"); + assertTransformedToString("@myAnno()" + EOL + "@myAnno2()" + EOL + "int foo();", it); + } + + @Test + public void removingAnnotationOnSomeLine() { + AnnotationMemberDeclaration it = consider("@myAnno int foo();"); + it.getAnnotations().remove(0); + assertTransformedToString("int foo();", it); + } + + @Test + public void removingAnnotationOnPrevLine() { + AnnotationMemberDeclaration it = consider("@myAnno" + EOL + "int foo();"); + it.getAnnotations().remove(0); + assertTransformedToString("int foo();", it); + } + + @Test + public void replacingAnnotation() { + AnnotationMemberDeclaration it = consider("@myAnno int foo();"); + it.getAnnotations().set(0, new NormalAnnotationExpr(new Name("myOtherAnno"), new NodeList<>())); + assertTransformedToString("@myOtherAnno() int foo();", it); + } + + // Javadoc + + @Test + public void addingJavadoc() { + AnnotationMemberDeclaration it = consider("int foo();"); + it.setJavadocComment("Cool this annotation!"); + assertTransformedToString("@interface AD { /** Cool this annotation!*/" + EOL + + "int foo(); }", it.getParentNode().get()); + } + + @Test + public void removingJavadoc() { + AnnotationMemberDeclaration it = consider("/** Cool this annotation!*/ int foo();"); + assertTrue(it.getJavadocComment().get().remove()); + assertTransformedToString("@interface AD { int foo(); }", it.getParentNode().get()); + } + + @Test + public void replacingJavadoc() { + AnnotationMemberDeclaration it = consider("/** Cool this annotation!*/ int foo();"); + it.setJavadocComment("Super extra cool this annotation!!!"); + assertTransformedToString("@interface AD { /** Super extra cool this annotation!!!*/ int foo(); }", it.getParentNode().get()); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java new file mode 100644 index 000000000..1be80378d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ClassOrInterfaceDeclarationTransformationsTest.java @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.ast.type.TypeParameter; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.utils.Utils.EOL; + +/** + * Transforming ClassOrInterfaceDeclaration and verifying the LexicalPreservation works as expected. + */ +public class ClassOrInterfaceDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected ClassOrInterfaceDeclaration consider(String code) { + considerCode(code); + return cu.getType(0).asClassOrInterfaceDeclaration(); + } + + // Name + + @Test + public void settingName() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setName("B"); + assertTransformedToString("class B {}", cid); + } + + // isInterface + + @Test + public void classToInterface() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setInterface(true); + assertTransformedToString("interface A {}", cid); + } + + @Test + public void interfaceToClass() throws IOException { + ClassOrInterfaceDeclaration cid = consider("interface A {}"); + cid.setInterface(false); + assertTransformedToString("class A {}", cid); + } + + // typeParameters + + @Test + public void addingTypeParameterWhenThereAreNone() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addTypeParameter(new TypeParameter("T", new NodeList<>())); + assertTransformedToString("class A<T> {}", cid); + } + + @Test + public void addingTypeParameterAsFirstWhenThereAreSome() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A<U> {}"); + cid.getTypeParameters().addFirst(new TypeParameter("T", new NodeList<>())); + assertTransformedToString("class A<T, U> {}", cid); + } + + @Test + public void addingTypeParameterAsLastWhenThereAreSome() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A<U> {}"); + cid.addTypeParameter(new TypeParameter("T", new NodeList<>())); + assertTransformedToString("class A<U, T> {}", cid); + } + + // extendedTypes + + @Test + public void addingExtendedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addExtendedType("Foo"); + assertTransformedToString("class A extends Foo {}", cid); + } + + @Test + public void removingExtendedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}"); + cid.getExtendedTypes().remove(0); + assertTransformedToString("public class A {}", cid); + } + + @Test + public void replacingExtendedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A extends Foo {}"); + cid.getExtendedTypes().set(0, parseClassOrInterfaceType("Bar")); + assertTransformedToString("public class A extends Bar {}", cid); + } + + // implementedTypes + + @Test + public void addingImplementedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addImplementedType("Foo"); + assertTransformedToString("class A implements Foo {}", cid); + } + + @Test + public void removingImplementedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}"); + cid.getImplementedTypes().remove(0); + assertTransformedToString("public class A {}", cid); + } + + @Test + public void replacingImplementedTypes() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A implements Foo {}"); + cid.getImplementedTypes().set(0, parseClassOrInterfaceType("Bar")); + assertTransformedToString("public class A implements Bar {}", cid); + } + + // Modifiers + + @Test + public void addingModifiers() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public class A {}", cid); + } + + @Test + public void removingModifiers() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A {}"); + cid.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("class A {}", cid); + } + + @Test + public void replacingModifiers() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A {}"); + cid.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected class A {}", cid); + } + + // members + + @Test + public void addingField() throws IOException { + ClassOrInterfaceDeclaration cid = consider("class A {}"); + cid.addField("int", "foo"); + assertTransformedToString("class A {" + EOL + " int foo;" + EOL + "}", cid); + } + + @Test + public void removingField() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A { int foo; }"); + cid.getMembers().remove(0); + assertTransformedToString("public class A {}", cid); + } + + @Test + public void replacingFieldWithAnotherField() throws IOException { + ClassOrInterfaceDeclaration cid = consider("public class A {float f;}"); + cid.getMembers().set(0, new FieldDeclaration(EnumSet.noneOf(Modifier.class), new VariableDeclarator(PrimitiveType.intType(), "bar"))); + assertTransformedToString("public class A {int bar;}", cid); + } + + // Annotations + + // Javadoc + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java new file mode 100644 index 000000000..6889a70ef --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/ConstructorDeclarationTransformationsTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +/** + * Transforming ConstructorDeclaration and verifying the LexicalPreservation works as expected. + */ +public class ConstructorDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected ConstructorDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asConstructorDeclaration(); + } + + // Name + + @Test + public void settingName() throws IOException { + ConstructorDeclaration cd = consider("A(){}"); + cd.setName("B"); + assertTransformedToString("B(){}", cd); + } + + // JavaDoc + + // Modifiers + + @Test + public void addingModifiers() throws IOException { + ConstructorDeclaration cd = consider("A(){}"); + cd.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public A(){}", cd); + } + + @Test + public void removingModifiers() throws IOException { + ConstructorDeclaration cd = consider("public A(){}"); + cd.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("A(){}", cd); + } + + @Test + public void replacingModifiers() throws IOException { + ConstructorDeclaration cd = consider("public A(){}"); + cd.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected A(){}", cd); + } + + // Parameters + + @Test + public void addingParameters() throws IOException { + ConstructorDeclaration cd = consider("A(){}"); + cd.addParameter(PrimitiveType.doubleType(), "d"); + assertTransformedToString("A(double d){}", cd); + } + + @Test + public void removingOnlyParameter() throws IOException { + ConstructorDeclaration cd = consider("public A(double d){}"); + cd.getParameters().remove(0); + assertTransformedToString("public A(){}", cd); + } + + @Test + public void removingFirstParameterOfMany() throws IOException { + ConstructorDeclaration cd = consider("public A(double d, float f){}"); + cd.getParameters().remove(0); + assertTransformedToString("public A(float f){}", cd); + } + + @Test + public void removingLastParameterOfMany() throws IOException { + ConstructorDeclaration cd = consider("public A(double d, float f){}"); + cd.getParameters().remove(1); + assertTransformedToString("public A(double d){}", cd); + } + + @Test + public void replacingOnlyParameter() throws IOException { + ConstructorDeclaration cd = consider("public A(float f){}"); + cd.getParameters().set(0, new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo"))); + assertTransformedToString("public A(int[] foo){}", cd); + } + + // ThrownExceptions + + // Body + + // Annotations +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java new file mode 100644 index 000000000..dff71cc3c --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumConstantDeclarationTransformationsTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; + +/** + * Transforming EnumConstantDeclaration and verifying the LexicalPreservation works as expected. + */ +public class EnumConstantDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected EnumConstantDeclaration consider(String code) { + considerCode("enum A { " + code + " }"); + return cu.getType(0).asEnumDeclaration().getEntries().get(0); + } + + // Name + + @Test + public void settingName() throws IOException { + EnumConstantDeclaration ecd = consider("A"); + ecd.setName("B"); + assertTransformedToString("B", ecd); + } + + // Annotations + + // Javadoc + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java new file mode 100644 index 000000000..e2a8fa3df --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/EnumDeclarationTransformationsTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +/** + * Transforming EnumDeclaration and verifying the LexicalPreservation works as expected. + */ +public class EnumDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected EnumDeclaration consider(String code) { + considerCode(code); + return cu.getType(0).asEnumDeclaration(); + } + + // Name + + @Test + public void settingName() throws IOException { + EnumDeclaration cid = consider("enum A { E1, E2 }"); + cid.setName("B"); + assertTransformedToString("enum B { E1, E2 }", cid); + } + + // implementedTypes + + // Modifiers + + @Test + public void addingModifiers() throws IOException { + EnumDeclaration ed = consider("enum A { E1, E2 }"); + ed.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public enum A { E1, E2 }", ed); + } + + @Test + public void removingModifiers() throws IOException { + EnumDeclaration ed = consider("public enum A { E1, E2 }"); + ed.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("enum A { E1, E2 }", ed); + } + + @Test + public void replacingModifiers() throws IOException { + EnumDeclaration ed = consider("public enum A { E1, E2 }"); + ed.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected enum A { E1, E2 }", ed); + } + + // members + + // Annotations + + // Javadoc + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java new file mode 100644 index 000000000..994f5d8b6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/FieldDeclarationTransformationsTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +/** + * Transforming FieldDeclaration and verifying the LexicalPreservation works as expected. + */ +public class FieldDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected FieldDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asFieldDeclaration(); + } + + // JavaDoc + + // Modifiers + + @Test + public void addingModifiers() { + FieldDeclaration it = consider("int A;"); + it.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public int A;", it); + } + + @Test + public void removingModifiers() { + FieldDeclaration it = consider("public int A;"); + it.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("int A;", it); + } + + @Test + public void replacingModifiers() { + FieldDeclaration it = consider("int A;"); + it.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected int A;", it); + } + + @Test + public void changingTypes() { + FieldDeclaration it = consider("int a, b;"); + assertTransformedToString("int a, b;", it); + it.getVariable(0).setType("Xyz"); + assertTransformedToString(" a, b;", it); + it.getVariable(1).setType("Xyz"); + assertTransformedToString("Xyz a, b;", it); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java new file mode 100644 index 000000000..738acb36d --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/InitializerDeclarationTransformationsTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.body.InitializerDeclaration; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; + +/** + * Transforming InitializerDeclaration and verifying the LexicalPreservation works as expected. + */ +public class InitializerDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected InitializerDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asInitializerDeclaration(); + } + + // JavaDoc + + // Body + + // IsStatic + + @Test + public void instanceToStatic() throws IOException { + InitializerDeclaration it = consider("{ /*some comment*/ }"); + it.setStatic(true); + assertTransformedToString("static { /*some comment*/ }", it); + } + + @Test + public void staticToInstance() throws IOException { + InitializerDeclaration it = consider("static { /*some comment*/ }"); + it.setStatic(false); + assertTransformedToString("{ /*some comment*/ }", it); + } + + // Annotations +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java new file mode 100644 index 000000000..1f94f3868 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/printer/lexicalpreservation/transformations/ast/body/MethodDeclarationTransformationsTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.printer.lexicalpreservation.transformations.ast.body; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.type.ArrayType; +import com.github.javaparser.ast.type.PrimitiveType; +import com.github.javaparser.printer.lexicalpreservation.AbstractLexicalPreservingTest; +import org.junit.Test; + +import java.io.IOException; +import java.util.EnumSet; + +/** + * Transforming MethodDeclaration and verifying the LexicalPreservation works as expected. + */ +public class MethodDeclarationTransformationsTest extends AbstractLexicalPreservingTest { + + protected MethodDeclaration consider(String code) { + considerCode("class A { " + code + " }"); + return cu.getType(0).getMembers().get(0).asMethodDeclaration(); + } + + // Name + + @Test + public void settingName() throws IOException { + MethodDeclaration it = consider("void A(){}"); + it.setName("B"); + assertTransformedToString("void B(){}", it); + } + + // JavaDoc + + // Modifiers + + @Test + public void addingModifiers() throws IOException { + MethodDeclaration it = consider("void A(){}"); + it.setModifiers(EnumSet.of(Modifier.PUBLIC)); + assertTransformedToString("public void A(){}", it); + } + + @Test + public void removingModifiers() throws IOException { + MethodDeclaration it = consider("public void A(){}"); + it.setModifiers(EnumSet.noneOf(Modifier.class)); + assertTransformedToString("void A(){}", it); + } + + @Test + public void replacingModifiers() throws IOException { + MethodDeclaration it = consider("public void A(){}"); + it.setModifiers(EnumSet.of(Modifier.PROTECTED)); + assertTransformedToString("protected void A(){}", it); + } + + // Parameters + + @Test + public void addingParameters() throws IOException { + MethodDeclaration it = consider("void foo(){}"); + it.addParameter(PrimitiveType.doubleType(), "d"); + assertTransformedToString("void foo(double d){}", it); + } + + @Test + public void removingOnlyParameter() throws IOException { + MethodDeclaration it = consider("public void foo(double d){}"); + it.getParameters().remove(0); + assertTransformedToString("public void foo(){}", it); + } + + @Test + public void removingFirstParameterOfMany() throws IOException { + MethodDeclaration it = consider("public void foo(double d, float f){}"); + it.getParameters().remove(0); + assertTransformedToString("public void foo(float f){}", it); + } + + @Test + public void removingLastParameterOfMany() throws IOException { + MethodDeclaration it = consider("public void foo(double d, float f){}"); + it.getParameters().remove(1); + assertTransformedToString("public void foo(double d){}", it); + } + + @Test + public void replacingOnlyParameter() throws IOException { + MethodDeclaration it = consider("public void foo(float f){}"); + it.getParameters().set(0, new Parameter(new ArrayType(PrimitiveType.intType()), new SimpleName("foo"))); + assertTransformedToString("public void foo(int[] foo){}", it); + } + + // ThrownExceptions + + // Body + + // Annotations +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java b/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java new file mode 100644 index 000000000..6620bb1c8 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/remove/NodeRemovalTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.remove; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.Statement; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class NodeRemovalTest { + private final CompilationUnit cu = new CompilationUnit(); + + @Test + public void testRemoveClassFromCompilationUnit() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + assertEquals(1, cu.getTypes().size()); + boolean remove = testClass.remove(); + assertEquals(true, remove); + assertEquals(0, cu.getTypes().size()); + } + + @Test + public void testRemoveFieldFromClass() { + ClassOrInterfaceDeclaration testClass = cu.addClass("test"); + + FieldDeclaration addField = testClass.addField(String.class, "test"); + assertEquals(1, testClass.getMembers().size()); + boolean remove = addField.remove(); + assertEquals(true, remove); + assertEquals(0, testClass.getMembers().size()); + } + + @Test + public void testRemoveStatementFromMethodBody() { + ClassOrInterfaceDeclaration testClass = cu.addClass("testC"); + + MethodDeclaration addMethod = testClass.addMethod("testM"); + BlockStmt methodBody = addMethod.createBody(); + Statement addStatement = methodBody.addAndGetStatement("test"); + assertEquals(1, methodBody.getStatements().size()); + boolean remove = addStatement.remove(); + assertEquals(true, remove); + assertEquals(0, methodBody.getStatements().size()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java new file mode 100644 index 000000000..dafe7ad0c --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/CodeGenerationUtilsTest.java @@ -0,0 +1,22 @@ +package com.github.javaparser.utils; + +import org.junit.Test; + +import static com.github.javaparser.utils.CodeGenerationUtils.*; +import static org.junit.Assert.*; + +public class CodeGenerationUtilsTest { + @Test + public void setters() { + assertEquals("setValue", setterName("value")); + assertEquals("setBlue", setterName("isBlue")); + } + + @Test + public void getters() { + assertEquals("getValue", getterName(Object.class, "value")); + assertEquals("isBlue", getterName(Boolean.class, "isBlue")); + assertEquals("isBlue", getterName(Boolean.class, "blue")); + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java new file mode 100644 index 000000000..2a5b84aa2 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/PairTest.java @@ -0,0 +1,21 @@ +package com.github.javaparser.utils; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PairTest { + @Test + public void testToString() { + Pair<String, String> pair = new Pair<>("abc", "def"); + + assertEquals("<abc, def>", pair.toString()); + } + + @Test + public void testToStringNulls() { + Pair<String, String> pair = new Pair<>(null, null); + + assertEquals("<null, null>", pair.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java new file mode 100644 index 000000000..a0bb50e2e --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceRootTest.java @@ -0,0 +1,38 @@ +package com.github.javaparser.utils; + +import com.github.javaparser.ParseResult; +import com.github.javaparser.ast.CompilationUnit; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SourceRootTest { + private final Path root = CodeGenerationUtils.classLoaderRoot(SourceRootTest.class).resolve("com/github/javaparser/utils/"); + private final SourceRoot sourceRoot = new SourceRoot(root); + + @Test + public void parseTestDirectory() throws IOException { + + List<ParseResult<CompilationUnit>> parseResults = sourceRoot.tryToParse(); + List<CompilationUnit> units = sourceRoot.getCompilationUnits(); + + assertEquals(2, units.size()); + assertTrue(units.stream().allMatch(unit -> !unit.getTypes().isEmpty() || unit.getModule().isPresent())); + assertTrue(parseResults.stream().anyMatch(cu -> cu.getResult().get().getStorage().get().getPath().toString().contains("source" + File.separator + "root"))); + } + + @Test(expected = IllegalArgumentException.class) + public void fileAsRootIsNotAllowed() { + Path path = CodeGenerationUtils.classLoaderRoot(SourceRootTest.class).resolve("/com/github/javaparser/utils/Bla.java"); + new SourceRoot(path); + } + + + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java new file mode 100644 index 000000000..05e80aba0 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/SourceZipTest.java @@ -0,0 +1,81 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import com.github.javaparser.ParseResult;
+import com.github.javaparser.ast.CompilationUnit;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class SourceZipTest {
+
+ private final Path testDir = CodeGenerationUtils.mavenModuleRoot(SourceZipTest.class)
+ .resolve(Paths.get("..", "javaparser-testing", "src", "test", "resources", "com", "github", "javaparser",
+ "source_zip"))
+ .normalize();
+
+ @Test
+ public void parseTestDirectory() throws URISyntaxException, IOException {
+ SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip"));
+ List<Pair<Path, ParseResult<CompilationUnit>>> results = sourceZip.parse();
+ assertEquals(3, results.size());
+ List<CompilationUnit> units = new ArrayList<>();
+ for (Pair<Path, ParseResult<CompilationUnit>> pr : results) {
+ units.add(pr.b.getResult().get());
+ }
+ assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty()));
+ }
+
+ @Test
+ public void parseTestDirectoryWithCallback() throws URISyntaxException, IOException {
+ SourceZip sourceZip = new SourceZip(testDir.resolve("test.zip"));
+ List<Pair<Path, ParseResult<CompilationUnit>>> results = new ArrayList<>();
+
+ sourceZip.parse((path, result) -> results.add(new Pair<>(path, result)));
+
+ assertEquals(3, results.size());
+ List<CompilationUnit> units = new ArrayList<>();
+ for (Pair<Path, ParseResult<CompilationUnit>> pr : results) {
+ units.add(pr.b.getResult().get());
+ }
+ assertTrue(units.stream().noneMatch(unit -> unit.getTypes().isEmpty()));
+ }
+
+ @Test(expected = IOException.class)
+ public void dirAsZipIsNotAllowed() throws IOException {
+ new SourceZip(testDir.resolve("test")).parse();
+ }
+
+ @Test(expected = IOException.class)
+ public void fileAsZipIsNotAllowed() throws IOException {
+ new SourceZip(testDir.resolve("test.txt")).parse();
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java new file mode 100644 index 000000000..24f17670a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/TestUtils.java @@ -0,0 +1,155 @@ +package com.github.javaparser.utils; + +import com.github.javaparser.*; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.validator.Java9Validator; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.*; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static com.github.javaparser.ParserConfiguration.LanguageLevel.*; +import static com.github.javaparser.Providers.provider; +import static com.github.javaparser.utils.CodeGenerationUtils.f; +import static com.github.javaparser.utils.Utils.EOL; +import static com.github.javaparser.utils.Utils.normalizeEolInTextBlock; +import static java.util.Arrays.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +public class TestUtils { + /** + * Takes care of setting all the end of line character to platform specific ones. + */ + public static String readResource(String resourceName) throws IOException { + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + try (final InputStream resourceAsStream = TestUtils.class.getClassLoader().getResourceAsStream(resourceName)) { + if (resourceAsStream == null) { + fail("not found: " + resourceName); + } + try (final InputStreamReader reader = new InputStreamReader(resourceAsStream, "utf-8"); + final BufferedReader br = new BufferedReader(reader)) { + final StringBuilder builder = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + builder.append(line).append(Utils.EOL); + } + return builder.toString(); + } + } + } + + public static void assertInstanceOf(Class<?> expectedType, Object instance) { + assertEquals(true, expectedType.isAssignableFrom(instance.getClass()), f("%s is not an instance of %s.", instance.getClass(), expectedType)); + } + + /** + * Unzip a zip file into a directory. + */ + public static void unzip(Path zipFile, Path outputFolder) throws IOException { + Log.info("Unzipping %s to %s", zipFile, outputFolder); + + final byte[] buffer = new byte[1024 * 1024]; + + outputFolder.toFile().mkdirs(); + + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile.toFile()))) { + ZipEntry ze = zis.getNextEntry(); + + while (ze != null) { + final Path newFile = outputFolder.resolve(ze.getName()); + + if (ze.isDirectory()) { + Log.trace("mkdir %s", newFile.toAbsolutePath()); + newFile.toFile().mkdirs(); + } else { + Log.info("unzip %s", newFile.toAbsolutePath()); + try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) { + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } + } + zis.closeEntry(); + ze = zis.getNextEntry(); + } + + } + Log.info("Unzipped %s to %s", zipFile, outputFolder); + } + + /** + * Download a file from a URL to disk. + */ + public static void download(URL url, Path destination) throws IOException { + OkHttpClient client = new OkHttpClient(); + Request request = new Request.Builder() + .url(url) + .build(); + + Response response = client.newCall(request).execute(); + Files.write(destination, response.body().bytes()); + } + + public static String temporaryDirectory() { + return System.getProperty("java.io.tmpdir"); + } + + public static void assertCollections(Collection<?> expected, Collection<?> actual) { + final StringBuilder out = new StringBuilder(); + for (Object e : expected) { + if (actual.contains(e)) { + actual.remove(e); + } else { + out.append("Missing: ").append(e).append(EOL); + } + } + for (Object a : actual) { + out.append("Unexpected: ").append(a).append(EOL); + } + + String s = out.toString(); + if (s.isEmpty()) { + return; + } + fail(s); + } + + public static void assertProblems(ParseResult<?> result, String... expectedArg) { + assertProblems(result.getProblems(), expectedArg); + } + + public static void assertProblems(List<Problem> result, String... expectedArg) { + Set<String> actual = result.stream().map(Problem::toString).collect(Collectors.toSet()); + Set<String> expected = new HashSet<>(asList(expectedArg)); + assertCollections(expected, actual); + } + + public static void assertNoProblems(ParseResult<?> result) { + assertProblems(result); + } + + public static void assertExpressionValid(String expression) { + JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9)); + ParseResult<Expression> result = javaParser.parse(ParseStart.EXPRESSION, provider(expression)); + assertEquals(true, result.isSuccessful(), result.getProblems().toString()); + } + + /** + * Assert that "actual" equals "expected", and that any EOL characters in "actual" are correct for the platform. + */ + public static void assertEqualsNoEol(String expected, String actual) { + assertEquals(normalizeEolInTextBlock(expected, EOL), actual); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java new file mode 100644 index 000000000..21ecf4cc2 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/UtilsTest.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.utils; + +import org.junit.Test; + +import static com.github.javaparser.utils.Utils.*; +import static org.junit.Assert.assertEquals; + +public class UtilsTest { + + @Test + public void testScreamingToCamelCase() { + assertEquals("abc", screamingToCamelCase("ABC")); + assertEquals("abcDef", screamingToCamelCase("ABC_DEF")); + assertEquals("abc", screamingToCamelCase("ABC_")); + } + + @Test + public void screamingEmptyString() { + assertEquals("", camelCaseToScreaming("")); + assertEquals("ABC", camelCaseToScreaming("abc")); + assertEquals("HELLO_HELLO", camelCaseToScreaming("HelloHello")); + assertEquals("APE_TAIL", camelCaseToScreaming("apeTail")); + } + + @Test(expected = IllegalArgumentException.class) + public void capitalizeOnEmptyString() { + capitalize(""); + } + + @Test + public void capitalizeOnStringOfOneCharacter() { + assertEquals("F", capitalize("f")); + } + + @Test + public void capitalizeOnStringOfTwoCharacters() { + assertEquals("Fo", capitalize("fo")); + } + + @Test(expected = IllegalArgumentException.class) + public void decapitalizeOnEmptyString() { + decapitalize(""); + } + + @Test + public void decapitalizeOnStringOfOneCharacter() { + assertEquals("f", decapitalize("F")); + } + + @Test + public void decapitalizeOnStringOfTwoCharacters() { + assertEquals("fo", decapitalize("Fo")); + } + + @Test + public void normalizeEolInTextBlock() { + String result = Utils.normalizeEolInTextBlock("\r\n \r \n", "Q"); + assertEquals("Q Q Q", result); + } + + @Test + public void testTrimTrailingSpaces() { + assertEquals("abc", trimTrailingSpaces("abc")); + assertEquals(" abc", trimTrailingSpaces(" abc")); + assertEquals("abc", trimTrailingSpaces("abc ")); + assertEquals(" abc", trimTrailingSpaces(" abc ")); + assertEquals("abc", trimTrailingSpaces("abc\t\0")); + assertEquals("", trimTrailingSpaces(" ")); + assertEquals("", trimTrailingSpaces("")); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java new file mode 100644 index 000000000..c0944ec07 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorListTest.java @@ -0,0 +1,187 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor;
+import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor;
+
+public class VisitorListTest {
+
+ @Test
+ public void visitorAddAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ for (int i = 0; i < list.size(); i++)
+ assertEquals(list.get(i), vList.get(i));
+ }
+
+ @Test
+ public void visitorAddAllAtIndex() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class Y{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.add(JavaParser.parse("class A{}"));
+ vList.add(JavaParser.parse("class B{}"));
+ vList.addAll(2, list);
+ vList.add(JavaParser.parse("class C{}"));
+ for (int i = 0; i < list.size(); i++)
+ assertEquals(list.get(i), vList.get(2 + i));
+ }
+
+ @Test
+ public void visitorListContains() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(x1);
+ assertTrue(list.contains(x1));
+ }
+
+ @Test
+ public void visitorListContainsAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ assertTrue(vList.size() == 2 && vList.containsAll(list));
+ }
+
+ @Test
+ public void visitorListIterator() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ list.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ list.add(x2);
+ Iterator<CompilationUnit> itr = list.iterator();
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 1);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 0);
+ }
+
+ @Test
+ public void visitorListListIterator() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ list.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ list.add(x2);
+ Iterator<CompilationUnit> itr = list.listIterator(2);
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 3);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(list.size() == 2);
+ }
+
+ @Test
+ public void visitorListRemove() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(x1);
+ assertTrue(list.remove(x1));
+ }
+
+ @Test
+ public void visitorListRemoveAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ vList.removeAll(list);
+ assertTrue(vList.size() == 0);
+ }
+
+ @Test
+ public void visitorListRetainAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ VisitorList<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ vList.add(JavaParser.parse("class X{}"));
+ vList.retainAll(list);
+ assertTrue(vList.size() == 2);
+ }
+
+ @Test
+ public void visitorListSubList() {
+ VisitorList<CompilationUnit> list = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ assertTrue(list.size() == 4);
+ List<CompilationUnit> subLst = list.subList(1, 3);
+ assertTrue(subLst.size() == 2);
+ subLst.add(JavaParser.parse("class X{}"));
+ assertTrue(subLst.size() == 3);
+ assertTrue(list.size() == 5);
+
+ }
+
+ @Test
+ public void visitorListToArray() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ List<CompilationUnit> vList = new VisitorList<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ vList.addAll(list);
+ for (CompilationUnit u : vList.toArray(new CompilationUnit[2]))
+ assertTrue(vList.contains(u));
+ }
+
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java new file mode 100644 index 000000000..03d4b7b65 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorMapTest.java @@ -0,0 +1,80 @@ +package com.github.javaparser.utils; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor; +import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class VisitorMapTest { + @Test + public void normalEqualsDoesDeepCompare() { + CompilationUnit x1 = JavaParser.parse("class X{}"); + CompilationUnit x2 = JavaParser.parse("class X{}"); + + Map<CompilationUnit, Integer> map = new HashMap<>(); + map.put(x1, 1); + map.put(x2, 2); + assertEquals(1, map.size()); + } + + @Test + public void objectIdentityEqualsDoesShallowCompare() { + CompilationUnit x1 = JavaParser.parse("class X{}"); + CompilationUnit x2 = JavaParser.parse("class X{}"); + + Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + map.put(x2, 2); + assertEquals(2, map.size()); + } + + @Test + public void visitorMapGet(){ + CompilationUnit x1 = JavaParser.parse("class X{}"); + + Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertEquals(1, (int)map.get(x1)); + } + + @Test + public void visitorMapContainsKey(){ + CompilationUnit x1 = JavaParser.parse("class X{}"); + + Map<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertTrue(map.containsKey(x1)); + } + + @Test + public void visitorMapPutAll(){ + CompilationUnit x1 = JavaParser.parse("class X{}"); + CompilationUnit x2 = JavaParser.parse("class Y{}"); + Map<CompilationUnit, Integer> map = new HashMap<>(); + map.put(x1, 1); + map.put(x2, 2); + Map<CompilationUnit, Integer> visitorMap = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + visitorMap.putAll(map); + assertEquals(2, visitorMap.size()); + } + + @Test + public void remove(){ + CompilationUnit x1 = JavaParser.parse("class X{}"); + VisitorMap<CompilationUnit, Integer> map = new VisitorMap<>(new ObjectIdentityHashCodeVisitor(), new ObjectIdentityEqualsVisitor()); + map.put(x1, 1); + assertTrue(map.containsKey(x1)); + + map.remove(x1); + + assertFalse(map.containsKey(x1)); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java new file mode 100644 index 000000000..1d7730b97 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/utils/VisitorSetTest.java @@ -0,0 +1,141 @@ +/*
+ * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
+ * Copyright (C) 2011, 2013-2016 The JavaParser Team.
+ *
+ * This file is part of JavaParser.
+ *
+ * JavaParser can be used either under the terms of
+ * a) the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * b) the terms of the Apache License
+ *
+ * You should have received a copy of both licenses in LICENCE.LGPL and
+ * LICENCE.APACHE. Please refer to those files for details.
+ *
+ * JavaParser is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ */
+
+package com.github.javaparser.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+
+import com.github.javaparser.JavaParser;
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.visitor.ObjectIdentityEqualsVisitor;
+import com.github.javaparser.ast.visitor.ObjectIdentityHashCodeVisitor;
+
+public class VisitorSetTest {
+
+ @Test
+ public void normalEqualsDoesDeepCompare() {
+ Set<CompilationUnit> set = new HashSet<>();
+ set.add(JavaParser.parse("class X{}"));
+ set.add(JavaParser.parse("class X{}"));
+ assertEquals(1, set.size());
+ }
+
+ @Test
+ public void objectIdentityEqualsDoesShallowCompare() {
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(JavaParser.parse("class X{}"));
+ set.add(JavaParser.parse("class X{}"));
+ assertEquals(2, set.size());
+ }
+
+ @Test
+ public void visitorSetContains() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(x1);
+ assertTrue(set.contains(x1));
+ }
+
+ @Test
+ public void visitorSetContainsAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ assertTrue(set.size() == 2 && set.containsAll(list));
+ }
+
+ @Test
+ public void visitorSetIterator() {
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ set.add(x1);
+ CompilationUnit x2 = JavaParser.parse("class X{}");
+ set.add(x2);
+ Iterator<CompilationUnit> itr = set.iterator();
+ assertEquals(x1, itr.next());
+ itr.remove();
+ assertTrue(set.size() == 1);
+ assertEquals(x2, itr.next());
+ itr.remove();
+ assertTrue(set.size() == 0);
+ }
+
+ @Test
+ public void visitorSetRemove() {
+ CompilationUnit x1 = JavaParser.parse("class X{}");
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.add(x1);
+ assertTrue(set.remove(x1));
+ }
+
+ @Test
+ public void visitorSetRemoveAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ set.removeAll(list);
+ assertTrue(set.size() == 0);
+ }
+
+ @Test
+ public void visitorSetRetainAll() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ set.add(JavaParser.parse("class X{}"));
+ set.retainAll(list);
+ assertTrue(set.size() == 2);
+ }
+
+ @Test
+ public void visitorSetToArray() {
+ List<CompilationUnit> list = new ArrayList<>();
+ list.add(JavaParser.parse("class X{}"));
+ list.add(JavaParser.parse("class X{}"));
+ Set<CompilationUnit> set = new VisitorSet<>(new ObjectIdentityHashCodeVisitor(),
+ new ObjectIdentityEqualsVisitor());
+ set.addAll(list);
+ for (CompilationUnit u : set.toArray(new CompilationUnit[2]))
+ assertTrue(set.contains(u));
+ }
+}
diff --git a/javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java new file mode 100644 index 000000000..4f9af2748 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/version/Java10PostProcessorTest.java @@ -0,0 +1,28 @@ +package com.github.javaparser.version; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ast.stmt.Statement; +import com.github.javaparser.ast.type.VarType; +import org.junit.Test; + +import java.util.List; + +import static com.github.javaparser.ParseStart.STATEMENT; +import static com.github.javaparser.ParserConfiguration.LanguageLevel.JAVA_10; +import static com.github.javaparser.Providers.provider; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class Java10PostProcessorTest { + public static final JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_10)); + + @Test + public void varIsAType() { + ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("var x=\"\";")); + + List<VarType> allVarTypes = result.getResult().get().findAll(VarType.class); + + assertEquals(1, allVarTypes.size()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java new file mode 100644 index 000000000..677cfcc51 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithAVisitorTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.junit.Test; + +public class ChangingMethodsFromAClassWithAVisitorTest { + @Test + public void printingTheCompilationUnitToSystemOutput() throws Exception { + try (TestFileToken f = new TestFileToken("test.java")) { + MethodChanger_1.main(new String[]{}); + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java new file mode 100644 index 000000000..9301ff58b --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ChangingMethodsFromAClassWithoutAVisitorTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.junit.Test; + +public class ChangingMethodsFromAClassWithoutAVisitorTest { + @Test + public void printingTheCompilationUnitToSystemOutput() throws Exception { + try (TestFileToken f = new TestFileToken("test.java")) { + MethodChanger_2.main(new String[]{}); + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java new file mode 100644 index 000000000..1e1d91b59 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/ClassCreator.java @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.expr.*; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.VoidType; + +import java.util.EnumSet; + +import static com.github.javaparser.JavaParser.parseClassOrInterfaceType; +import static com.github.javaparser.JavaParser.parseName; + +public class ClassCreator { + + public static void main(String[] args) throws Exception { + // creates the compilation unit + CompilationUnit cu = createCU(); + + // prints the created compilation unit + System.out.println(cu.toString()); + } + + /** + * creates the compilation unit + */ + private static CompilationUnit createCU() { + CompilationUnit cu = new CompilationUnit(); + // set the package + cu.setPackageDeclaration(new PackageDeclaration(parseName("java.parser.test"))); + + // or a shortcut + cu.setPackageDeclaration("java.parser.test"); + + // create the type declaration + ClassOrInterfaceDeclaration type = cu.addClass("GeneratedClass"); + + // create a method + EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC); + MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), "main"); + modifiers.add(Modifier.STATIC); + method.setModifiers(modifiers); + type.addMember(method); + + // or a shortcut + MethodDeclaration main2 = type.addMethod("main2", Modifier.PUBLIC, Modifier.STATIC); + + // add a parameter to the method + Parameter param = new Parameter(parseClassOrInterfaceType("String"), "args"); + param.setVarArgs(true); + method.addParameter(param); + + // or a shortcut + main2.addAndGetParameter(String.class, "args").setVarArgs(true); + + // add a body to the method + BlockStmt block = new BlockStmt(); + method.setBody(block); + + // add a statement to the method body + NameExpr clazz = new NameExpr("System"); + FieldAccessExpr field = new FieldAccessExpr(clazz, "out"); + MethodCallExpr call = new MethodCallExpr(field, "println"); + call.addArgument(new StringLiteralExpr("Hello World!")); + block.addStatement(call); + + return cu; + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java new file mode 100644 index 000000000..fa256d2ff --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CreatingACompilationUnitFromScratch.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.junit.Test; + +public class CreatingACompilationUnitFromScratch { + @Test + public void printingTheCompilationUnitToSystemOutput() throws Exception { + ClassCreator.main(new String[]{}); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java new file mode 100644 index 000000000..89653f4f6 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/CuPrinter.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; + +import java.io.FileInputStream; + +public class CuPrinter { + + public static void main(String[] args) throws Exception { + // creates an input stream for the file to be parsed + FileInputStream in = new FileInputStream("test.java"); + + // parse the file + CompilationUnit cu = JavaParser.parse(in); + + // prints the resulting compilation unit to default system output + System.out.println(cu.toString()); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java new file mode 100644 index 000000000..1d64866e1 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_1.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import java.io.File; + +public class MethodChanger_1 { + + public static void main(String[] args) throws Exception { + // parse a file + CompilationUnit cu = JavaParser.parse(new File("test.java")); + + // visit and change the methods names and parameters + cu.accept(new MethodChangerVisitor(), null); + + // prints the changed compilation unit + System.out.println(cu); + } + + /** + * Simple visitor implementation for visiting MethodDeclaration nodes. + */ + private static class MethodChangerVisitor extends VoidVisitorAdapter<Void> { + @Override + public void visit(MethodDeclaration n, Void arg) { + // change the name of the method to upper case + n.setName(n.getNameAsString().toUpperCase()); + + // add a new parameter to the method + n.addParameter("int", "value"); + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java new file mode 100644 index 000000000..bf0c72d7a --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodChanger_2.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; + +import java.io.FileInputStream; + +import static com.github.javaparser.ast.type.PrimitiveType.intType; + +public class MethodChanger_2 { + + public static void main(String[] args) throws Exception { + // creates an input stream for the file to be parsed + FileInputStream in = new FileInputStream("test.java"); + + // parse the file + CompilationUnit cu = JavaParser.parse(in); + + // change the methods names and parameters + changeMethods(cu); + + // prints the changed compilation unit + System.out.println(cu.toString()); + } + + private static void changeMethods(CompilationUnit cu) { + // Go through all the types in the file + NodeList<TypeDeclaration<?>> types = cu.getTypes(); + for (TypeDeclaration<?> type : types) { + // Go through all fields, methods, etc. in this type + NodeList<BodyDeclaration<?>> members = type.getMembers(); + for (BodyDeclaration<?> member : members) { + if (member instanceof MethodDeclaration) { + MethodDeclaration method = (MethodDeclaration) member; + changeMethod(method); + } + } + } + } + + private static void changeMethod(MethodDeclaration n) { + // change the name of the method to upper case + n.setName(n.getNameAsString().toUpperCase()); + + // create the new parameter + n.addParameter(intType(), "value"); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java new file mode 100644 index 000000000..8e1e5bf98 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/MethodPrinter.java @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; + +import java.io.FileInputStream; + +public class MethodPrinter { + + public static void main(String[] args) throws Exception { + // creates an input stream for the file to be parsed + FileInputStream in = new FileInputStream("test.java"); + + // parse it + CompilationUnit cu = JavaParser.parse(in); + + // visit and print the methods names + cu.accept(new MethodVisitor(), null); + } + + /** + * Simple visitor implementation for visiting MethodDeclaration nodes. + */ + private static class MethodVisitor extends VoidVisitorAdapter<Void> { + @Override + public void visit(MethodDeclaration n, Void arg) { + /* here you can access the attributes of the method. + this method will be called for all methods in this + CompilationUnit, including inner class methods */ + System.out.println(n.getName()); + super.visit(n, arg); + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java new file mode 100644 index 000000000..26a907e27 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/PrintingTheCompilationUnitToSystemOutputTest.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.junit.Test; + +public class PrintingTheCompilationUnitToSystemOutputTest { + @Test + public void printingTheCompilationUnitToSystemOutput() throws Exception { + try (TestFileToken f = new TestFileToken("test.java")) { + CuPrinter.main(new String[]{}); + } + } + +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java new file mode 100644 index 000000000..3227c3d8f --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/TestFileToken.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.apache.commons.io.IOUtils; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import static org.junit.Assert.*; + +/** + * Creates a temporary test file that a sample can use. This way we don't have to rewrite the samples to fit them into + * these tests. + */ +public class TestFileToken implements AutoCloseable { + private final String filename; + + public TestFileToken(String filename) { + this.filename = filename; + try { + try (InputStream i = getClass().getResourceAsStream("TestFile.java"); OutputStream o = new FileOutputStream(filename)) { + assertNotNull(i); + IOUtils.copy(i, o); + } + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Override + public void close() { + boolean deleted = new File(filename).delete(); + assertTrue(deleted); + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java new file mode 100644 index 000000000..599912411 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/VisitingClassMethodsTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples; + +import org.junit.Test; + +public class VisitingClassMethodsTest { + @Test + public void testCode() throws Exception { + try (TestFileToken f = new TestFileToken("test.java")) { + MethodPrinter.main(new String[]{}); + } + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java new file mode 100644 index 000000000..dd925bc35 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/D.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples.removenode; + +public class D { + + public void foo(int e) { + int a = 20; + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java new file mode 100644 index 000000000..d522c9625 --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/ModifierVisitorTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples.removenode; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.IntegerLiteralExpr; +import com.github.javaparser.ast.visitor.ModifierVisitor; + +import java.io.FileInputStream; + +public class ModifierVisitorTest { + + public static void main(String... args) throws Exception { + // parse the file + CompilationUnit cu = JavaParser.parse(new FileInputStream("forGitHubTest.java")); + + // The visitor should remove all a=20 variable declarations. + cu.accept(new MyVisitor(), null); + + System.out.println(cu.toString()); + } +} + +class MyVisitor extends ModifierVisitor<Void> { + @Override + public Node visit(VariableDeclarator declarator, Void args) { + if (declarator.getNameAsString().equals("a") + // the initializer is optional, first check if there is one + && declarator.getInitializer().isPresent()) { + Expression expression = declarator.getInitializer().get(); + // We're looking for a literal integer. + if (expression instanceof IntegerLiteralExpr) { + // We found one. Is it literal integer 20? + if (((IntegerLiteralExpr) expression).getValue().equals("20")) { + // Returning null means "remove this VariableDeclarator" + return null; + } + } + } + return declarator; + } +} diff --git a/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java new file mode 100644 index 000000000..72756e94f --- /dev/null +++ b/javaparser-testing/src/test/java/com/github/javaparser/wiki_samples/removenode/RemoveDeleteNodeFromAst.java @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2007-2010 Júlio Vilmar Gesser. + * Copyright (C) 2011, 2013-2016 The JavaParser Team. + * + * This file is part of JavaParser. + * + * JavaParser can be used either under the terms of + * a) the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * b) the terms of the Apache License + * + * You should have received a copy of both licenses in LICENCE.LGPL and + * LICENCE.APACHE. Please refer to those files for details. + * + * JavaParser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + */ + +package com.github.javaparser.wiki_samples.removenode; + +import com.github.javaparser.wiki_samples.TestFileToken; +import org.junit.Test; + +public class RemoveDeleteNodeFromAst { + @Test + public void testCode1() throws Exception { + try (TestFileToken f = new TestFileToken("forGitHubTest.java")) { + ModifierVisitorTest.main(); + } + } +} |