repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/JavaParsingHelper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.ast.SemanticException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.JavaParser;
import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor;
import net.sourceforge.pmd.lang.java.internal.JavaLanguageProcessor;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger.SimpleLogger;
import net.sourceforge.pmd.lang.java.types.internal.infer.TypeInferenceLogger.VerboseLogger;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
import kotlin.Pair;
public class JavaParsingHelper extends BaseParsingHelper<JavaParsingHelper, ASTCompilationUnit> {
/**
* Note: this is the default type system for everything parsed with
* default options of JavaParsingHelper. This allows constants like
* the null type to be compared.
*/
public static final TypeSystem TEST_TYPE_SYSTEM = TypeSystem.usingClassLoaderClasspath(JavaParsingHelper.class.getClassLoader());
/** This runs all processing stages when parsing. */
public static final JavaParsingHelper DEFAULT = new JavaParsingHelper(
Params.getDefault(),
SemanticErrorReporter.noop(), // todo change this to unforgiving logger, need to update a lot of tests
TEST_TYPE_SYSTEM,
TypeInferenceLogger.noop()
);
private final SemanticErrorReporter semanticLogger;
private final TypeSystem ts;
private final TypeInferenceLogger typeInfLogger;
private JavaParsingHelper(Params params, SemanticErrorReporter logger, TypeSystem ts, TypeInferenceLogger typeInfLogger) {
super(JavaLanguageModule.NAME, ASTCompilationUnit.class, params);
this.semanticLogger = logger;
this.ts = ts;
this.typeInfLogger = typeInfLogger;
}
@Override
protected @NonNull ASTCompilationUnit doParse(@NotNull LanguageProcessor processor, @NotNull Params params, @NotNull ParserTask task) {
@SuppressWarnings({ "PMD.CloseResource", "resource" })
JavaLanguageProcessor proc = (JavaLanguageProcessor) processor;
proc.setTypeSystem(ts);
JavaParser parser = proc.getParserWithoutProcessing();
ASTCompilationUnit rootNode = parser.parse(task);
if (params.getDoProcess()) {
JavaAstProcessor.process(proc, semanticLogger, typeInfLogger, rootNode);
}
return rootNode;
}
public TypeInferenceLogger getTypeInfLogger() {
return typeInfLogger;
}
public JavaParsingHelper withLogger(SemanticErrorReporter logger) {
return new JavaParsingHelper(this.getParams(), logger, this.ts, this.typeInfLogger);
}
public JavaParsingHelper withTypeSystem(TypeSystem ts) {
return new JavaParsingHelper(this.getParams(), this.semanticLogger, ts, this.typeInfLogger);
}
public JavaParsingHelper logTypeInference(boolean verbose, PrintStream out) {
return logTypeInference(verbose ? new VerboseLogger(out) : new SimpleLogger(out));
}
public JavaParsingHelper logTypeInference(TypeInferenceLogger logger) {
return new JavaParsingHelper(this.getParams(), this.semanticLogger, this.ts, logger);
}
public JavaParsingHelper logTypeInferenceVerbose() {
return logTypeInference(true, System.out);
}
@Override
protected @NonNull JavaParsingHelper clone(@NonNull Params params) {
return new JavaParsingHelper(params, semanticLogger, ts, typeInfLogger);
}
public static class TestCheckLogger implements SemanticErrorReporter {
public final Map<String, List<kotlin.Pair<Node, Object[]>>> warnings = new HashMap<>();
public final Map<String, List<kotlin.Pair<Node, Object[]>>> errors = new HashMap<>();
private final SemanticErrorReporter baseLogger;
public TestCheckLogger(boolean doLogOnConsole) {
this(defaultMessageReporter(doLogOnConsole));
}
public TestCheckLogger(SemanticErrorReporter baseLogger) {
this.baseLogger = baseLogger;
}
private static SemanticErrorReporter defaultMessageReporter(boolean doLog) {
if (!doLog) {
return SemanticErrorReporter.noop();
}
Logger consoleLogger = LoggerFactory.getLogger(TestCheckLogger.class);
MessageReporter reporter = new SimpleMessageReporter(consoleLogger);
return SemanticErrorReporter.reportToLogger(reporter);
}
@Override
public void warning(Node location, String message, Object... args) {
warnings.computeIfAbsent(message, k -> new ArrayList<>())
.add(new Pair<>(location, args));
baseLogger.warning(location, message, args);
}
@Override
public SemanticException error(Node location, String message, Object... args) {
errors.computeIfAbsent(message, k -> new ArrayList<>())
.add(new Pair<>(location, args));
return baseLogger.error(location, message, args);
}
@Override
public @Nullable SemanticException getFirstError() {
return baseLogger.getFirstError();
}
}
/**
* Will throw on the first semantic error or warning.
* Useful because it produces a stack trace for that warning/error.
*/
public static class UnforgivingSemanticLogger implements SemanticErrorReporter {
private static final int MAX_NODE_TEXT_WIDTH = 100;
public static final UnforgivingSemanticLogger INSTANCE = new UnforgivingSemanticLogger();
private UnforgivingSemanticLogger() {
}
@Override
public void warning(Node location, String message, Object... formatArgs) {
String warning = MessageFormat.format(message, formatArgs);
throw new AssertionError(
"Expected no warnings, but got: " + warning + "\n"
+ "at " + StringUtils.truncate(location.toString(), 100)
);
}
@Override
public SemanticException error(Node location, String message, Object... formatArgs) {
String error = MessageFormat.format(message, formatArgs);
throw new AssertionError(
"Expected no errors, but got: " + error + "\n"
+ "at " + StringUtils.truncate(location.toString(), MAX_NODE_TEXT_WIDTH)
);
}
@Override
public @Nullable SemanticException getFirstError() {
return null;
}
}
}
| 7,577 | 38.061856 | 139 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/QuickstartRulesetTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class QuickstartRulesetTest {
@Test
void noDeprecations() throws Exception {
RuleSetLoader ruleSetLoader = new RuleSetLoader().enableCompatibility(false);
String errorOutput = SystemLambda.tapSystemErr(() -> {
RuleSet quickstart = ruleSetLoader.loadFromResource("rulesets/java/quickstart.xml");
assertFalse(quickstart.getRules().isEmpty());
});
assertTrue(errorOutput.isEmpty());
}
}
| 877 | 29.275862 | 96 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/PMD5RulesetTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
class PMD5RulesetTest {
@Test
void loadRuleset() {
RuleSet ruleset = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/lang/java/pmd5ruleset.xml");
assertNotNull(ruleset);
assertNull(ruleset.getRuleByName("GuardLogStatementJavaUtil"));
assertNull(ruleset.getRuleByName("GuardLogStatement"));
}
}
| 715 | 27.64 | 112 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymArray;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
class SymbolicValueTest {
static final TypeSystem TS = JavaParsingHelper.TEST_TYPE_SYSTEM;
@Test
void testSymValueEquality() {
assertEquals(symValueOf(new String[] {"ddd", "eee"}),
ofArray(symValueOf("ddd"), symValueOf("eee")),
"Array of strings");
assertEquals(symValueOf(new boolean[] {true}),
symValueOf(new boolean[] {true}),
"Array of booleans");
assertNotEquals(symValueOf(new boolean[] {true}),
symValueOf(new boolean[] {false}),
"Array of booleans");
assertTrue(symValueOf(new int[] {10, 11}).valueEquals(new int[] {10, 11}),
"valueEquals for int[]");
assertTrue(symValueOf(new boolean[] {false}).valueEquals(new boolean[] {false}),
"valueEquals for boolean[]");
assertFalse(symValueOf(new int[] {10, 11}).valueEquals(new int[] {10}),
"valueEquals for int[]");
assertFalse(symValueOf(new int[] {10, 11}).valueEquals(new double[] {10, 11}),
"valueEquals for double[] 2");
assertFalse(symValueOf(new int[] {}).valueEquals(new double[] {}),
"valueEquals for empty arrays");
assertTrue(symValueOf(new double[] {}).valueEquals(new double[] {}),
"valueEquals for empty arrays");
}
// test only
static SymbolicValue symValueOf(Object o) {
return SymbolicValue.of(TS, o);
}
static SymbolicValue ofArray(SymbolicValue... values) {
return SymArray.forElements(Arrays.asList(values.clone()));
}
}
| 2,307 | 33.969697 | 88 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/ClassLoadingChildFirstTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.internal.util.ClasspathClassLoader;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* @author Clément Fournier
*/
class ClassLoadingChildFirstTest {
/**
* In this test I packed a jar with a custom version of {@link Void}.
* The test asserts that when putting that jar on the auxclasspath,
* a {@link TypeSystem} prefers that custom class to the one on the
* bootstrap classpath. The functionality under test is actually in
* {@link ClasspathClassLoader}.
*
* <p>The jar file "custom_java_lang.jar" also contains the sources
* for the custom class {@code java.lang.Void}.
* </p>
*/
@Test
void testClassLoading() {
Path file = Paths.get("src/test/resources",
getClass().getPackage().getName().replace('.', '/'),
"custom_java_lang.jar");
PMDConfiguration config = new PMDConfiguration();
config.prependAuxClasspath(file.toAbsolutePath().toString());
TypeSystem typeSystem = TypeSystem.usingClassLoaderClasspath(config.getClassLoader());
JClassType voidClass = typeSystem.BOXED_VOID;
List<JMethodSymbol> declaredMethods = voidClass.getSymbol().getDeclaredMethods();
assertThat(declaredMethods, hasSize(1));
assertThat(declaredMethods.get(0), hasProperty("simpleName", equalTo("customMethodOnJavaLangVoid")));
}
}
| 1,962 | 32.844828 | 109 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/AnnotationReflectionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols;
import static java.util.Collections.emptySet;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.createAnnotationInstance;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.getMethodSym;
import static net.sourceforge.pmd.util.CollectionUtil.mapOf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static net.sourceforge.pmd.util.OptionalBool.NO;
import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN;
import static net.sourceforge.pmd.util.OptionalBool.YES;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.Objects;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.pcollections.PSet;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.internal.SymImplementation;
import net.sourceforge.pmd.lang.java.symbols.testdata.AnnotWithDefaults;
import net.sourceforge.pmd.lang.java.symbols.testdata.ConstructorAnnotation;
import net.sourceforge.pmd.lang.java.symbols.testdata.FieldAnnotation;
import net.sourceforge.pmd.lang.java.symbols.testdata.LocalVarAnnotation;
import net.sourceforge.pmd.lang.java.symbols.testdata.MethodAnnotation;
import net.sourceforge.pmd.lang.java.symbols.testdata.ParameterAnnotation;
import net.sourceforge.pmd.lang.java.symbols.testdata.SomeClass;
class AnnotationReflectionTest {
@ParameterizedTest
@EnumSource
void testReflectionOfClassMethods(SymImplementation impl) {
Class<SomeClass> actualClass = SomeClass.class;
JClassSymbol sym = impl.getSymbol(actualClass);
impl.assertAllMethodsMatch(actualClass, sym);
impl.assertAllFieldsMatch(actualClass, sym);
}
@ParameterizedTest
@EnumSource
void testReflectionOfAnnotDefaults(SymImplementation impl) {
Class<AnnotWithDefaults> actualClass = AnnotWithDefaults.class;
JClassSymbol sym = impl.getSymbol(actualClass);
impl.assertAllMethodsMatch(actualClass, sym);
}
@ParameterizedTest
@EnumSource
void testAnnotUseThatUsesDefaults(SymImplementation impl) {
// note that as the annotation has retention class, we can't use reflection to check
/*
@AnnotWithDefaults(valueNoDefault = "ohio",
stringArrayDefault = {})
*/
JClassSymbol sym = impl.getSymbol(SomeClass.class);
assertTrue(sym.isAnnotationPresent(AnnotWithDefaults.class));
SymAnnot target = sym.getDeclaredAnnotation(AnnotWithDefaults.class);
// explicit values are known
assertEquals(YES, target.attributeMatches("valueNoDefault", "ohio"));
assertEquals(YES, target.attributeMatches("stringArrayDefault", new String[] { }));
assertEquals(NO, target.attributeMatches("stringArrayDefault", "0"));
// default values are also known
assertEquals(YES, target.attributeMatches("stringArrayEmptyDefault", new String[] { }));
assertEquals(NO, target.attributeMatches("stringArrayEmptyDefault", new String[] { "a" }));
// Non existing values are always considered unknown
assertEquals(UNKNOWN, target.attributeMatches("attributeDoesNotExist", new String[] { "a" }));
}
@ParameterizedTest
@EnumSource
void testAnnotOnAnnot(SymImplementation impl) {
// This only checks for Target.ANNOTATION_TYPE annotations
Class<AnnotWithDefaults> actualClass = AnnotWithDefaults.class;
JClassSymbol sym = impl.getSymbol(actualClass);
Target targetAnnot = createAnnotationInstance(Target.class, mapOf("value", new ElementType[] { ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD }));
assertHasAnnotations(setOf(targetAnnot), sym);
}
@ParameterizedTest
@EnumSource
void testAnnotOnParameter(SymImplementation impl) {
// This only checks Target.PARAMETER annotations, do not confuse with TYPE_PARAMETER / TYPE_USE
Class<SomeClass> actualClass = SomeClass.class;
JClassSymbol sym = impl.getSymbol(actualClass);
ParameterAnnotation annot = createAnnotationInstance(ParameterAnnotation.class);
JMethodSymbol method = getMethodSym(sym, "withAnnotatedParam");
assertHasAnnotations(emptySet(), method.getFormalParameters().get(0));
assertHasAnnotations(setOf(annot), method.getFormalParameters().get(1));
}
@ParameterizedTest
@EnumSource
void testAnnotOnField(SymImplementation impl) {
// This only checks Target.FIELD annotations, do not confuse with TYPE_USE annotations
Class<SomeClass> actualClass = SomeClass.class;
JClassSymbol sym = impl.getSymbol(actualClass);
JFieldSymbol f1 = sym.getDeclaredField("f1");
assertHasAnnotations(setOf(createAnnotationInstance(FieldAnnotation.class)), f1);
}
@ParameterizedTest
@EnumSource
void testAnnotOnMethod(SymImplementation impl) {
// This only checks Target.METHOD annotations, do not confuse with TYPE_USE on return types
Class<SomeClass> actualClass = SomeClass.class;
JClassSymbol sym = impl.getSymbol(actualClass);
JMethodSymbol method = getMethodSym(sym, "anotatedMethod");
assertHasAnnotations(emptySet(), method.getFormalParameters().get(0));
assertHasAnnotations(setOf(createAnnotationInstance(MethodAnnotation.class)), method);
}
@ParameterizedTest
@EnumSource
void testAnnotOnConstructor(SymImplementation impl) {
// This only checks Target.CONSTRUCTOR annotations, do not confuse with TYPE_USE on return types
Class<SomeClass> actualClass = SomeClass.class;
JClassSymbol sym = impl.getSymbol(actualClass);
JConstructorSymbol ctor = sym.getConstructors().get(0);
assertHasAnnotations(setOf(createAnnotationInstance(ConstructorAnnotation.class)), ctor);
}
@Test
void testAnnotOnLocalVar() {
// This only checks Target.LOCAL_VAR annotations, do not confuse with TYPE_USE on return types
JClassSymbol sym = SymImplementation.AST.getSymbol(SomeClass.class);
@NonNull JVariableSymbol localSym = Objects.requireNonNull(sym.tryGetNode())
.descendants(ASTVariableDeclaratorId.class)
.filter(it -> "local".equals(it.getName()))
.firstOrThrow()
.getSymbol();
assertHasAnnotations(setOf(createAnnotationInstance(LocalVarAnnotation.class)), localSym);
}
@Test
void testAnnotWithInvalidType() {
@NonNull ASTVariableDeclaratorId field =
JavaParsingHelper.DEFAULT.parse(
"@interface A {}\n"
+ "class C<A> { @A int a; }\n"
).descendants(ASTFieldDeclaration.class).firstOrThrow().getVarIds().firstOrThrow();
// The annotation actually refers to the type parameter A. Since
// this is invalid code, it is filtered out.
PSet<SymAnnot> annots = field.getSymbol().getDeclaredAnnotations();
assertThat(annots, empty());
}
private void assertHasAnnotations(Set<? extends Annotation> expected, AnnotableSymbol annotable) {
assertNotNull(annotable);
assertThat(annotable.getDeclaredAnnotations(), hasSize(expected.size()));
for (Annotation annot : expected) {
Class<? extends Annotation> annotType = annot.annotationType();
SymAnnot symAnnot = annotable.getDeclaredAnnotation(annotType);
assertEquals(SymbolicValue.of(annotable.getTypeSystem(), annot), symAnnot);
assertTrue(annotable.isAnnotationPresent(annotType));
assertTrue(symAnnot.isOfType(annotType));
assertTrue(symAnnot.valueEquals(annot));
assertTrue(symAnnot.isOfType(annotType.getName()));
}
}
}
| 8,878 | 42.52451 | 186 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTBlock;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.java.ast.ASTStatement;
class AbruptCompletionTests extends BaseParserTest {
private final JavaParsingHelper java17 = java.withDefaultVersion("17");
private Executable canCompleteNormally(String stmt, Consumer<Boolean> expected) {
return canCompleteNormally(stmt, (actual, ignored) -> expected.accept(actual), it -> it);
}
private Executable canCompleteNormally(String stmtText, BiConsumer<Boolean, ASTStatement> expected, Function<ASTBlock, ASTStatement> getNode) {
return () -> {
ASTCompilationUnit ast = java17.parse("class Foo {{ " + stmtText + "; }}");
ASTBlock block = ast.descendants(ASTBlock.class).crossFindBoundaries().firstOrThrow();
ASTStatement stmt = getNode.apply(block);
boolean actual = AbruptCompletionAnalysis.canCompleteNormally(stmt);
expected.accept(actual, stmt);
};
}
private Executable canCompleteNormally(String stmtText, boolean expected, Function<ASTBlock, ASTStatement> getNode) {
return canCompleteNormally(
stmtText,
(actual, stmt) -> assertEquals(expected, actual, "Can " + stmt.getText() + " complete normally?"),
getNode
);
}
private Executable canCompleteNormally(String stmt) {
return canCompleteNormally(stmt, actual -> {
if (!actual) {
fail("Code CAN complete normally: `" + stmt + "`");
}
});
}
private Executable mustCompleteAbruptly(String stmt) {
return canCompleteNormally(stmt, actual -> {
if (actual) {
fail("Code MUST complete abruptly: `" + stmt + "`");
}
});
}
@Test
void testIfStatements() {
assertAll(
canCompleteNormally(
"if (foo) {}"
+ "else { throw new Exception(); }"
),
canCompleteNormally(
"if (foo) { throw new Exception(); }"
),
mustCompleteAbruptly(
"if (foo) { throw new Exception(); }"
+ "else { throw new Exception(); }"
)
);
}
@Test
void testWhileStmt() {
assertAll(
canCompleteNormally("while(foo) { return; }"),
canCompleteNormally("while(foo) { break; }"),
canCompleteNormally("l: while(foo) { break; }"),
canCompleteNormally("l: while(foo) { break l; }"),
canCompleteNormally("l: while(foo) { if (x) break l; }"),
canCompleteNormally("while(true) { if (foo) break; }"),
canCompleteNormally("while(false) { return; }"),
mustCompleteAbruptly("while(true) { return; }"),
mustCompleteAbruptly("while(true) { }"),
canCompleteNormally("while(true) { break; }"),
mustCompleteAbruptly("while(true) { while(foo) break; }"),
canCompleteNormally("x: while(true) { while(foo) break x; }"),
mustCompleteAbruptly("while(true) { if (print()) return; }")
);
}
@Test
void testForLoop() {
assertAll(
canCompleteNormally("for(; foo; ) { return; }"),
canCompleteNormally("for(;foo;) { break; }"),
canCompleteNormally("l: for(;foo;) { break; }"),
canCompleteNormally("l: for(;foo;) { break l; }"),
canCompleteNormally("l: for(;foo;) { if (x) break l; }"),
canCompleteNormally("for(;true;) { if (foo) break; }"),
canCompleteNormally("for(;false;) { return; }"),
mustCompleteAbruptly("for(;true;) { return; }"),
mustCompleteAbruptly("for(;true;) { }"),
canCompleteNormally("for(;true;) { break; }"),
mustCompleteAbruptly("for(;true;) { while(foo) break; }"),
canCompleteNormally("x: for(;true;) { while(foo) break x; }"),
mustCompleteAbruptly("for(;true;) { if (print()) return; }")
);
}
@Test
void testDoLoop() {
assertAll(
canCompleteNormally("do { } while(foo);"),
canCompleteNormally("do { continue; } while(foo);"),
canCompleteNormally("do { break; } while(foo);"),
canCompleteNormally("do { break; } while(true);"),
mustCompleteAbruptly("do { return; } while(true);"),
mustCompleteAbruptly("do { if(foo) return; } while(true);"),
mustCompleteAbruptly("do { continue; } while(true);"),
mustCompleteAbruptly("do { return; } while(foo);")
);
}
@Test
void testForeachLoop() {
assertAll(
canCompleteNormally("for (int i : new int[]{}) { }"),
canCompleteNormally("for (int i : new int[]{}) { continue; }"),
canCompleteNormally("for (int i : new int[]{}) { break; }"),
canCompleteNormally("for (int i : new int[]{}) { return; }")
);
}
@Test
void testWhileContinue() {
assertAll(
canCompleteNormally("while(foo) { if (x) continue; }"),
// this is trivial, but the condition may have side-effects
canCompleteNormally("while(foo) { continue; }"),
canCompleteNormally("if (foo) while(foo) { continue; } "
+ "else throw e;"),
mustCompleteAbruptly("while(true) { continue; }")
);
}
@Test
void testSwitchFallthrough() {
assertAll(
canCompleteNormally("switch(foo) {}"),
canCompleteNormally("switch(foo) { case 1: break; }"),
canCompleteNormally("switch(foo) { case 1: break; case 2: foo(); }"),
canCompleteNormally("switch(foo) { case 1: return; case 2: foo(); }")
);
}
@Test
void testSwitchArrow() {
assertAll(
canCompleteNormally("switch(foo) {}"),
canCompleteNormally("switch(foo) { case 1 -> X; default-> X;}"),
canCompleteNormally("switch(foo) { case 1 -> throw X; }"),
canCompleteNormally("switch(foo) { case 1 -> throw X; }"),
mustCompleteAbruptly("switch(foo) { case 1 -> throw X; default-> throw X;}")
);
}
@Test
void testTry() {
assertAll(
canCompleteNormally("try {}"),
canCompleteNormally("try { foo(); }"),
canCompleteNormally("try {{}}"),
canCompleteNormally("try { } catch (Exception e) { }"),
canCompleteNormally("try { throw x; } catch (Exception e) { }"),
canCompleteNormally("try { return; } catch (Exception e) { }"),
canCompleteNormally("try { } catch (Exception e) { return; }"),
mustCompleteAbruptly("try { return; } catch (Exception e) { return; }"),
mustCompleteAbruptly("try { } catch (Exception e) { } finally { return; }"),
mustCompleteAbruptly("try { } catch (Exception e) { throw x; } finally { throw x; }"),
mustCompleteAbruptly("while(true) { "
+ "try { } finally { throw x; } "
+ "}"),
mustCompleteAbruptly("try {} finally { throw x; }"),
mustCompleteAbruptly("try { throw x; } finally { }"),
mustCompleteAbruptly("try { throw x; } finally { throw x; }")
);
}
@Test
void testSwitchExhaustive() {
assertAll(
// no default, even with exhaustive enum, means it can complete normally
canCompleteNormally("enum Local { A } Local a = Local.A;\n"
+ "switch(a) { case A: return; }"),
mustCompleteAbruptly("enum Local { A } Local a = Local.A;\n"
+ "switch(a) { case A: return; default: return; }")
);
}
@Test
void testYield() {
assertAll(
canCompleteNormally("int i = switch(1) {"
+ " case 1 -> { yield 1; }"
+ " default -> { yield 2; }"
+ "}"),
canCompleteNormally("int i = switch(1) {"
+ " case 1 -> { return; }"
+ " default -> { yield 2; }"
+ "}"),
canCompleteNormally(
"int i = switch(1) {"
+ " case 1 -> { return; }"
+ " default -> { if (x) yield 2; else yield 3; }"
+ "}",
false, // the if stmt must return abruptly because of yield
n -> n.descendants(ASTIfStatement.class).firstOrThrow()
)
);
}
@Test
void testFalseLoopIsUnreachable() {
assertAll(
canCompleteNormally("while(false) { }"),
canCompleteNormally("for(;false;) { }")
);
}
@Test
void testLabeledStmt() {
assertAll(
canCompleteNormally("l: if (foo) break l; else break l;"),
mustCompleteAbruptly("if (foo) break l; else break l;")
);
}
}
| 9,991 | 35.870849 | 147 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/PatternBindingsTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.table.internal;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.symbols.table.internal.PatternBindingsUtil.BindSet;
import net.sourceforge.pmd.util.CollectionUtil;
class PatternBindingsTests extends BaseParserTest {
private final JavaParsingHelper java17 = java.withDefaultVersion("17");
private Executable declares(String expr, Set<String> trueVars, Set<String> falseVars) {
return () -> {
ASTCompilationUnit ast = java17.parse("class Foo {{ Object o = (" + expr + "); }}");
ASTExpression e = ast.descendants(ASTExpression.class).crossFindBoundaries().firstOrThrow();
BindSet bindSet = PatternBindingsUtil.bindersOfExpr(e);
checkBindings(expr, trueVars, bindSet.getTrueBindings(), true);
checkBindings(expr, falseVars, bindSet.getFalseBindings(), false);
};
}
private void checkBindings(String expr, Set<String> expected, Set<ASTVariableDeclaratorId> bindings, boolean isTrue) {
Set<String> actual = CollectionUtil.map(toSet(), bindings, ASTVariableDeclaratorId::getName);
assertEquals(expected, actual, "Bindings of '" + expr + "' when " + isTrue);
}
private Executable declaresNothing(String expr) {
return declares(expr, emptySet(), emptySet());
}
@Test
void testUnaries() {
String stringS = "a instanceof String s";
assertAll(
declares(stringS, setOf("s"), emptySet()),
declares("!(" + stringS + ")", emptySet(), setOf("s")),
declaresNothing("foo(" + stringS + ")"),
declaresNothing("foo(" + stringS + ") || true")
);
}
@Test
void testBooleanConditionals() {
String stringS = "(a instanceof String s)";
String stringP = "(a instanceof String p)";
assertAll(
declares(stringS + " || " + stringP, emptySet(), emptySet()),
declares(stringS + " && " + stringP, setOf("s", "p"), emptySet()),
declares("!(" + stringS + " || " + stringP + ")", emptySet(), emptySet()),
declares("!(" + stringS + " && " + stringP + ")", emptySet(), setOf("s", "p")),
declares("!" + stringS + " || " + stringP, emptySet(), setOf("s")),
declares("!" + stringS + " || !" + stringP, emptySet(), setOf("s", "p")),
declares("!" + stringS + " && !" + stringP, emptySet(), emptySet()),
declares(stringS + " && !" + stringP, setOf("s"), emptySet())
);
}
}
| 3,294 | 38.698795 | 122 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsInside.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.List;
/**
* See {@link net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotReflectionTest}.
*
* @author Clément Fournier
*/
@SuppressWarnings("all")
public class ClassWithTypeAnnotationsInside {
@A int intField;
@A List<String> annotOnList;
List<@A String> annotOnListArg;
@A List<@A String> annotOnBothListAndArg;
@A int[] annotOnArrayComponent;
int @A [] annotOnArrayDimension;
// this annotates the int[]
int[] @A @B [] twoAnnotsOnOuterArrayDim;
int @A [][] annotOnInnerArrayDim;
int @A(1) [] @A(2) [] annotsOnBothArrayDims;
Outer.@A Inner1 inner1WithAnnot;
@A Outer.@B Inner1 inner1WithAnnotOnOuterToo;
@A Outer.@B Inner1.Inner2 inner2WithAnnotOnBothOuter;
@A Outer.@A @B Inner1.@B Inner2 inner2WithAnnotOnAll;
Outer.@A @B Inner1.@A Inner2 inner2WithAnnotOnAllExceptOuter;
OuterG<T, T>.@A Inner5 annotOnInnerWithOuterGeneric;
OuterG<@A T, T>.@A Inner5 annotOnOuterGenericArg;
OuterG<T, @A T>.@A Inner5 annotOnOuterGenericArg2;
@A OuterG<T, @A T>.Inner5 annotOnOuterGenericArgAndOuter;
@A OuterG<T, @A T>.@A InnerG<@A T> annotOnOuterGenericArgAndInner;
OuterG<@A ? extends @B String, ? super @A @B T> severalWildcards;
@A OuterG<@A @B ? extends @B String, @A List<@A @B Object>> complicatedField;
@Target({ ElementType.TYPE_USE, ElementType.TYPE_PARAMETER })
public @interface A {
int value() default 1;
}
@Target({ ElementType.TYPE_USE, ElementType.TYPE_PARAMETER })
public @interface B { }
private static class T { }
static class Outer {
class Inner1 {
class Inner2 { }
}
}
static class OuterG<A, B> {
class Inner5 { }
class InnerG<X> { }
}
}
| 1,999 | 24 | 86 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/MethodAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {
}
| 422 | 20.15 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/FieldAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldAnnotation {
}
| 420 | 20.05 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ConstructorAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
public @interface ConstructorAnnotation {
}
| 432 | 20.65 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/TypeAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TypeAnnotation {
}
| 418 | 19.95 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/AnnotationWithNoRetention.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
public @interface AnnotationWithNoRetention {
}
| 194 | 18.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ParameterAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ParameterAnnotation {
}
| 417 | 23.588235 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsOnMethods.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.io.Serializable;
import java.util.List;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsInside.A;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsInside.B;
/**
* See {@link TypeAnnotReflectionOnMethodsTest}.
*
* @author Clément Fournier
*/
public abstract class ClassWithTypeAnnotationsOnMethods {
abstract void aOnIntParam(@A int i);
abstract void aOnStringParam(@A String i);
abstract @A @B String abOnReturn(@A String i);
abstract List<@A String> abOnReturnInArg();
abstract void aOnThrows() throws @A Exception;
// tparams
abstract <@A @B T, E extends T> void abOnTypeParm();
abstract <@A @B T, E extends T> T abOnTypeParm2(T t);
// tparam bounds
abstract <@A T, E extends @B T> E bOnTypeParmBound(T t);
abstract <@A T, E extends @B Cloneable & @A Serializable> E bOnTypeParmBoundIntersection(T t);
abstract void abOnReceiver(@A @B ClassWithTypeAnnotationsOnMethods this);
static class CtorOwner {
CtorOwner(@A @B int i) { }
@A CtorOwner() { }
CtorOwner(String i) throws @A Exception {}
}
}
| 1,314 | 23.811321 | 98 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/LocalVarAnnotation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.LOCAL_VARIABLE)
public @interface LocalVarAnnotation {
}
| 432 | 20.65 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/SomeClass.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
@TypeAnnotation
@AnnotWithDefaults(valueNoDefault = "ohio",
stringArrayDefault = {})
public class SomeClass {
@FieldAnnotation
private int f1;
@ConstructorAnnotation
public SomeClass() {
}
void withAnnotatedParam(int a, @ParameterAnnotation final String foo) {
}
void withAnnotatedLocal() {
@LocalVarAnnotation
long local;
}
@MethodAnnotation
void anotatedMethod(final int x) {
}
}
| 643 | 17.4 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/AnnotWithDefaults.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.testdata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
*
*/
@Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
public @interface AnnotWithDefaults {
String valueNoDefault();
String valueWithDefault() default "ddd";
String[] stringArrayDefault() default {"ddd"};
String[] stringArrayEmptyDefault() default {};
MyEnum[] enumArr() default {MyEnum.AA, MyEnum.BB};
MyEnum enumSimple() default MyEnum.AA;
Class<?> classAttr() default String.class;
enum MyEnum {
AA, BB, CC
}
}
| 738 | 19.527778 | 89 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOTS_A_B;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOT_A;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOT_B;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.assertHasTypeAnnots;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.getFieldType;
import static net.sourceforge.pmd.util.CollectionUtil.emptyList;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static net.sourceforge.pmd.util.CollectionUtil.mapOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsInside;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsInside.A;
import net.sourceforge.pmd.lang.java.types.JArrayType;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JWildcardType;
/**
*
*/
class TypeAnnotReflectionTest {
@ParameterizedTest
@EnumSource
void testTypeAnnotsOnFields(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
assertHasTypeAnnots(getFieldType(sym, "intField"), ANNOT_A);
assertHasTypeAnnots(getFieldType(sym, "annotOnList"), ANNOT_A);
{
JClassType t = (JClassType) getFieldType(sym, "annotOnListArg");
assertHasTypeAnnots(t, emptyList());
assertHasTypeAnnots(t.getTypeArgs().get(0), ANNOT_A);
}
{
JClassType t = (JClassType) getFieldType(sym, "annotOnBothListAndArg");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getTypeArgs().get(0), ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testArrayTypeAnnotsOnFields(SymImplementation impl) {
/*
@A int[] annotOnArrayComponent;
int @A [] annotOnArrayDimension;
// this annotates the int[]
int[] @A @B [] twoAnnotsOnOuterArrayDim;
int @A [][] annotOnInnerArrayDim;
int @A(1) [] @A(2) [] annotsOnBothArrayDims;
*/
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
{
JArrayType t = (JArrayType) getFieldType(sym, "annotOnArrayComponent");
assertHasTypeAnnots(t, emptyList());
assertHasTypeAnnots(t.getComponentType(), ANNOT_A);
assertHasTypeAnnots(t.getElementType(), ANNOT_A);
}
{
JArrayType t = (JArrayType) getFieldType(sym, "annotOnArrayDimension");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getComponentType(), emptyList());
assertHasTypeAnnots(t.getElementType(), emptyList());
}
{
// int[] @A @B []
JArrayType t = (JArrayType) getFieldType(sym, "twoAnnotsOnOuterArrayDim");
assertHasTypeAnnots(t, emptyList());
assertHasTypeAnnots(t.getComponentType(), ANNOTS_A_B);
assertHasTypeAnnots(t.getElementType(), emptyList());
}
{
// int @A(1) [] @A(2) [] annotsOnBothArrayDims;
JArrayType t = (JArrayType) getFieldType(sym, "annotsOnBothArrayDims");
assertHasTypeAnnots(t, listOf(makeAnA(1)));
assertHasTypeAnnots(t.getComponentType(), listOf(makeAnA(2)));
assertHasTypeAnnots(t.getElementType(), emptyList());
}
}
private static @NonNull A makeAnA(int v0) {
return TypeAnnotTestUtil.createAnnotationInstance(A.class, mapOf("value", v0));
}
@ParameterizedTest
@EnumSource
void testInnerTypeAnnotsOnFields(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
/*
Outer. @A Inner1 inner1WithAnnot;
@A Outer. @B Inner1 inner1WithAnnotOnOuterToo;
@A Outer. @B Inner1.Inner2 inner2WithAnnotOnBothOuter;
@A Outer. @A @B Inner1. @B Inner2 inner2WithAnnotOnAll;
Outer. @A @B Inner1. @A Inner2 inner2WithAnnotOnAllExceptOuter;
*/
{
JClassType t = (JClassType) getFieldType(sym, "inner1WithAnnot");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), emptyList());
}
{
JClassType t = (JClassType) getFieldType(sym, "inner1WithAnnotOnOuterToo");
assertHasTypeAnnots(t, ANNOT_B);
assertHasTypeAnnots(t.getEnclosingType(), ANNOT_A);
assertNull(t.getEnclosingType().getEnclosingType());
}
{
JClassType t = (JClassType) getFieldType(sym, "inner2WithAnnotOnBothOuter");
assertHasTypeAnnots(t, emptyList());
assertHasTypeAnnots(t.getEnclosingType(), ANNOT_B);
assertHasTypeAnnots(t.getEnclosingType().getEnclosingType(), ANNOT_A);
}
{
JClassType t = (JClassType) getFieldType(sym, "inner2WithAnnotOnAll");
assertHasTypeAnnots(t, ANNOT_B);
assertHasTypeAnnots(t.getEnclosingType(), ANNOTS_A_B);
assertHasTypeAnnots(t.getEnclosingType().getEnclosingType(), ANNOT_A);
}
{
JClassType t = (JClassType) getFieldType(sym, "inner2WithAnnotOnAllExceptOuter");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), ANNOTS_A_B);
assertHasTypeAnnots(t.getEnclosingType().getEnclosingType(), emptyList());
}
}
@ParameterizedTest
@EnumSource
void testInnerTypeAnnotsWithGenerics(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
/*
OuterG<A, T>.@A Inner5 annotOnInnerWithOuterGeneric;
OuterG<@A T, T>.@A Inner5 annotOnOuterGenericArg;
OuterG<A, @A T>.@A Inner5 annotOnOuterGenericArg2;
@A OuterG<A, @A T>.Inner5 annotOnOuterGenericArgAndOuter;
@A OuterG<A, @A T>.@A InnerG<@A T> annotOnOuterGenericArgAndInner;
*/
{
JClassType t = (JClassType) getFieldType(sym, "annotOnInnerWithOuterGeneric");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), emptyList());
}
{
JClassType t = (JClassType) getFieldType(sym, "annotOnOuterGenericArg");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(0), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(1), emptyList());
}
{
JClassType t = (JClassType) getFieldType(sym, "annotOnOuterGenericArg2");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(0), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(1), ANNOT_A);
}
{
JClassType t = (JClassType) getFieldType(sym, "annotOnOuterGenericArgAndOuter");
assertHasTypeAnnots(t, emptyList());
assertHasTypeAnnots(t.getEnclosingType(), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(0), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(1), ANNOT_A);
}
{
JClassType t = (JClassType) getFieldType(sym, "annotOnOuterGenericArgAndInner");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getTypeArgs().get(0), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(0), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(1), ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnMultipleGenericsAndInner(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
/*
@A OuterG<A, @A T>.@A InnerG<@A T> annotOnOuterGenericArgAndInner;
*/
{
JClassType t = (JClassType) getFieldType(sym, "annotOnOuterGenericArgAndInner");
assertHasTypeAnnots(t, ANNOT_A);
assertHasTypeAnnots(t.getTypeArgs().get(0), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType(), ANNOT_A);
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(0), emptyList());
assertHasTypeAnnots(t.getEnclosingType().getTypeArgs().get(1), ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnWildcards(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class);
/*
OuterG<@A @B ? extends @B String, ? super @A @B T> severalWildcards;
@A OuterG<@A @B ? extends @B String, @A List<@A @B Object>> complicatedField;
*/
{
JClassType t = (JClassType) getFieldType(sym, "severalWildcards");
assertHasTypeAnnots(t, emptyList());
JWildcardType wild0 = (JWildcardType) t.getTypeArgs().get(0);
assertHasTypeAnnots(wild0, ANNOT_A);
assertTrue(wild0.isUpperBound());
assertHasTypeAnnots(wild0.getBound(), ANNOT_B);
JWildcardType wild1 = (JWildcardType) t.getTypeArgs().get(1);
assertHasTypeAnnots(wild1, emptyList());
assertTrue(wild1.isLowerBound());
assertHasTypeAnnots(wild1.getBound(), ANNOTS_A_B);
}
{
JClassType t = (JClassType) getFieldType(sym, "complicatedField");
assertHasTypeAnnots(t, ANNOT_A);
JWildcardType wild0 = (JWildcardType) t.getTypeArgs().get(0);
assertHasTypeAnnots(wild0, ANNOTS_A_B);
assertTrue(wild0.isUpperBound());
assertHasTypeAnnots(wild0.getBound(), ANNOT_B);
JClassType arg1 = (JClassType) t.getTypeArgs().get(1);
assertHasTypeAnnots(arg1, ANNOT_A);
assertHasTypeAnnots(arg1.getTypeArgs().get(0), ANNOTS_A_B);
}
}
}
| 10,799 | 38.852399 | 99 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotTestUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.AnnotationUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import net.sourceforge.pmd.lang.java.symbols.AnnotableSymbol;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymAnnot;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsInside;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
/**
*
*/
public class TypeAnnotTestUtil {
static final List<Annotation> ANNOT_A = listOf(createAnnotationInstance(ClassWithTypeAnnotationsInside.A.class));
static final List<Annotation> ANNOT_B = listOf(createAnnotationInstance(ClassWithTypeAnnotationsInside.B.class));
static final List<Annotation> ANNOTS_A_B = listOf(ANNOT_A.get(0), ANNOT_B.get(0));
private TypeAnnotTestUtil() {
// utility class
}
public static JTypeMirror getFieldType(JClassType sym, String fieldName) {
return sym.getDeclaredField(fieldName).getTypeMirror();
}
public static JMethodSig getMethodType(JClassType sym, String fieldName) {
return sym.streamMethods(it -> it.nameEquals(fieldName)).findFirst().get();
}
public static JMethodSymbol getMethodSym(JClassSymbol sym, String fieldName) {
return sym.getDeclaredMethods().stream().filter(it -> it.nameEquals(fieldName)).findFirst().get();
}
public static void assertHasTypeAnnots(JTypeMirror t, List<Annotation> annots) {
assertNotNull(t);
assertThat(t.getTypeAnnotations(), equalTo(annots.stream().map(a -> SymbolicValue.of(t.getTypeSystem(), a)).collect(Collectors.toSet())));
}
public static void assertHasAnnots(AnnotableSymbol t, List<Annotation> annots) {
assertNotNull(t);
assertThat(t.getDeclaredAnnotations(), equalTo(annots.stream().map(a -> SymbolicValue.of(t.getTypeSystem(), a)).collect(Collectors.toSet())));
}
public static <A extends Annotation> A createAnnotationInstance(Class<A> annotationClass) {
return createAnnotationInstance(annotationClass, Collections.emptyMap());
}
/**
* Creates a fake instance of the annotation class using a {@link Proxy}.
* The proxy tries to be a faithful implementation of an annotation, albeit simple.
* It can use the provided map to get attribute values. If an attribute is
* not provided in the map, it will use the default value defined on the
* method declaration. If there is no defined default value, the invocation
* will fail.
*/
@SuppressWarnings("unchecked")
public static <A extends Annotation> A createAnnotationInstance(Class<A> annotationClass, Map<String, Object> attributes) {
return (A) Proxy.newProxyInstance(annotationClass.getClassLoader(), new Class[] { annotationClass }, (proxy, method, args) -> {
if (method.getName().equals("annotationType") && args == null) {
return annotationClass;
} else if (method.getName().equals("toString") && args == null) {
return AnnotationUtils.toString((Annotation) proxy);
} else if (method.getName().equals("hashCode") && args == null) {
return AnnotationUtils.hashCode((Annotation) proxy);
} else if (method.getName().equals("equals") && args.length == 1) {
if (args[0] instanceof Annotation) {
return AnnotationUtils.equals((Annotation) proxy, (Annotation) args[0]);
}
return false;
} else if (attributes.containsKey(method.getName()) && args == null) {
return attributes.get(method.getName());
} else if (method.getDefaultValue() != null && args == null) {
return method.getDefaultValue();
}
throw new UnsupportedOperationException("Proxy does not implement " + method);
});
}
private static Matcher<SymAnnot> matchesAnnot(Annotation o) {
return new BaseMatcher<SymAnnot>() {
@Override
public boolean matches(Object actual) {
return actual instanceof SymAnnot && ((SymAnnot) actual).valueEquals(o);
}
@Override
public void describeTo(Description description) {
description.appendText("an annotation like " + o);
}
};
}
}
| 5,219 | 40.76 | 150 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/SymImplementation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.symbols.JClassSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol;
import net.sourceforge.pmd.lang.java.symbols.JFormalParamSymbol;
import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol;
import net.sourceforge.pmd.lang.java.symbols.SymbolicValue;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.java.types.Substitution;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
/**
* Abstracts over which symbol implementation to use. Allows running
* the same tests with different implementations of the symbol.
* Use with {@link ParameterizedTest} and {@link EnumSource}.
*/
public enum SymImplementation {
ASM {
@Override
public @NonNull JClassSymbol getSymbol(Class<?> aClass) {
return Objects.requireNonNull(JavaParsingHelper.TEST_TYPE_SYSTEM.getClassSymbol(aClass), aClass.getName());
}
},
AST {
@Override
public @NonNull JClassSymbol getSymbol(Class<?> aClass) {
ASTCompilationUnit ast = JavaParsingHelper.DEFAULT.parseClass(aClass);
JClassSymbol symbol = ast.getTypeDeclarations().first(it -> it.getSimpleName().equals(aClass.getSimpleName())).getSymbol();
return Objects.requireNonNull(symbol, aClass.getName());
}
@Override
public JClassType getDeclaration(Class<?> aClass) {
ASTCompilationUnit ast = JavaParsingHelper.DEFAULT.parseClass(aClass);
return ast.getTypeDeclarations().first(it -> it.getSimpleName().equals(aClass.getSimpleName())).getTypeMirror();
}
@Override
public boolean supportsDebugSymbols() {
return true;
}
};
public boolean supportsDebugSymbols() {
return false;
}
public abstract @NonNull JClassSymbol getSymbol(Class<?> aClass);
public JClassType getDeclaration(Class<?> aClass) {
JClassSymbol symbol = getSymbol(aClass);
return (JClassType) symbol.getTypeSystem().declaration(symbol);
}
public void assertAllFieldsMatch(Class<?> actualClass, JClassSymbol sym) {
List<JFieldSymbol> fs = sym.getDeclaredFields();
Set<Field> actualFields = Arrays.stream(actualClass.getDeclaredFields()).filter(f -> !f.isSynthetic()).collect(Collectors.toSet());
assertEquals(actualFields.size(), fs.size());
for (final Field f : actualFields) {
JFieldSymbol fSym = fs.stream().filter(it -> it.getSimpleName().equals(f.getName()))
.findFirst().orElseThrow(AssertionError::new);
// Type matches
final JTypeMirror expectedType = typeMirrorOf(sym.getTypeSystem(), f.getType());
assertEquals(expectedType, fSym.getTypeMirror(Substitution.EMPTY));
assertEquals(f.getModifiers(), fSym.getModifiers());
}
}
private static JTypeMirror typeMirrorOf(TypeSystem ts, Class<?> type) {
return ts.declaration(ts.getClassSymbol(type));
}
public void assertAllMethodsMatch(Class<?> actualClass, JClassSymbol sym) {
List<JMethodSymbol> ms = sym.getDeclaredMethods();
Set<Method> actualMethods = Arrays.stream(actualClass.getDeclaredMethods()).filter(m -> !m.isSynthetic()).collect(Collectors.toSet());
assertEquals(actualMethods.size(), ms.size());
for (final Method m : actualMethods) {
JMethodSymbol mSym = ms.stream().filter(it -> it.getSimpleName().equals(m.getName()))
.findFirst().orElseThrow(AssertionError::new);
assertMethodMatch(m, mSym);
}
}
public void assertMethodMatch(Method m, JMethodSymbol mSym) {
assertEquals(m.getParameterCount(), mSym.getArity());
final Parameter[] parameters = m.getParameters();
List<JFormalParamSymbol> formals = mSym.getFormalParameters();
for (int i = 0; i < m.getParameterCount(); i++) {
assertParameterMatch(parameters[i], formals.get(i));
}
// Defaults should match too (even if not an annotation method, both should be null)
assertEquals(SymbolicValue.of(mSym.getTypeSystem(), m.getDefaultValue()), mSym.getDefaultAnnotationValue());
}
private void assertParameterMatch(Parameter p, JFormalParamSymbol pSym) {
if (supportsDebugSymbols()) {
if (p.isNamePresent()) {
assertEquals(p.getName(), pSym.getSimpleName());
assertEquals(Modifier.isFinal(p.getModifiers()), pSym.isFinal());
} else {
System.out.println("WARN: test classes were not compiled with -parameters, parameters not fully checked");
}
} else {
// note that this asserts, that the param names are unavailable
assertEquals("", pSym.getSimpleName());
assertFalse(pSym.isFinal());
}
// Ensure type matches
final JTypeMirror expectedType = typeMirrorOf(pSym.getTypeSystem(), p.getType());
assertEquals(expectedType, pSym.getTypeMirror(Substitution.EMPTY));
}
}
| 6,011 | 39.348993 | 142 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionOnMethodsTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.symbols.internal;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOTS_A_B;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOT_A;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.ANNOT_B;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.assertHasAnnots;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.assertHasTypeAnnots;
import static net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotTestUtil.getMethodType;
import static net.sourceforge.pmd.util.CollectionUtil.emptyList;
import static org.hamcrest.MatcherAssert.assertThat;
import org.hamcrest.Matchers;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import net.sourceforge.pmd.lang.java.symbols.testdata.ClassWithTypeAnnotationsOnMethods;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.JIntersectionType;
import net.sourceforge.pmd.lang.java.types.JMethodSig;
/**
*
*/
class TypeAnnotReflectionOnMethodsTest {
@ParameterizedTest
@EnumSource
void testTypeAnnotOnParameter(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract void aOnIntParam(@A int i);
abstract void aOnStringParam(@A String i);
*/
{
JMethodSig t = getMethodType(sym, "aOnIntParam");
assertHasTypeAnnots(t.getFormalParameters().get(0), ANNOT_A);
assertHasTypeAnnots(t.getReturnType(), emptyList());
}
{
JMethodSig t = getMethodType(sym, "aOnStringParam");
assertHasTypeAnnots(t.getFormalParameters().get(0), ANNOT_A);
assertHasTypeAnnots(t.getReturnType(), emptyList());
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnReturn(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract @A @B String abOnReturn(@A String i);
abstract List<@A String> abOnReturnInArg();
*/
{
JMethodSig t = getMethodType(sym, "abOnReturn");
assertHasTypeAnnots(t.getFormalParameters().get(0), ANNOT_A);
assertHasTypeAnnots(t.getReturnType(), ANNOTS_A_B);
}
{
JMethodSig t = getMethodType(sym, "abOnReturnInArg");
assertHasTypeAnnots(((JClassType) t.getReturnType()).getTypeArgs().get(0),
ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnThrows(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract void aOnThrows() throws @A RuntimeException;
*/
{
JMethodSig t = getMethodType(sym, "aOnThrows");
assertHasTypeAnnots(t.getReturnType(), emptyList());
assertHasTypeAnnots(t.getThrownExceptions().get(0), ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnTParam(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract <@A @B T, E extends T> void abOnTypeParm();
abstract <@A @B T, E extends T> T abOnTypeParm2(T t);
*/
{
JMethodSig t = getMethodType(sym, "abOnTypeParm");
assertHasTypeAnnots(t.getTypeParameters().get(0), emptyList());
assertHasAnnots(t.getTypeParameters().get(0).getSymbol(), ANNOTS_A_B);
assertHasTypeAnnots(t.getTypeParameters().get(1), emptyList());
}
{
JMethodSig t = getMethodType(sym, "abOnTypeParm2");
assertHasTypeAnnots(t.getTypeParameters().get(0), emptyList());
assertHasAnnots(t.getTypeParameters().get(0).getSymbol(), ANNOTS_A_B);
assertHasTypeAnnots(t.getTypeParameters().get(1), emptyList());
assertHasTypeAnnots(t.getReturnType(), emptyList());
assertHasTypeAnnots(t.getFormalParameters().get(0), emptyList());
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnTParamBound(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract <@A T, E extends @B T> E bOnTypeParmBound(T t);
abstract <@A T, E extends @B Cloneable & @A Serializable> E bOnTypeParmBoundIntersection(T t);
*/
{
JMethodSig t = getMethodType(sym, "bOnTypeParmBound");
assertHasTypeAnnots(t.getTypeParameters().get(0), emptyList());
assertHasAnnots(t.getTypeParameters().get(0).getSymbol(), ANNOT_A);
assertHasTypeAnnots(t.getTypeParameters().get(1), emptyList());
assertHasTypeAnnots(t.getTypeParameters().get(1).getUpperBound(), ANNOT_B);
assertHasTypeAnnots(t.getReturnType(), emptyList());
assertHasTypeAnnots(t.getFormalParameters().get(0), emptyList());
assertHasAnnots(t.getFormalParameters().get(0).getSymbol(), ANNOT_A);
}
{
JMethodSig t = getMethodType(sym, "bOnTypeParmBoundIntersection");
assertHasTypeAnnots(t.getTypeParameters().get(0), emptyList());
assertHasAnnots(t.getTypeParameters().get(0).getSymbol(), ANNOT_A);
assertHasTypeAnnots(t.getTypeParameters().get(1), emptyList());
assertHasTypeAnnots(t.getFormalParameters().get(0), emptyList());
assertHasAnnots(t.getFormalParameters().get(0).getSymbol(), ANNOT_A);
JIntersectionType ub = (JIntersectionType) t.getTypeParameters().get(1).getUpperBound();
assertHasTypeAnnots(ub, emptyList());
assertHasTypeAnnots(ub.getComponents().get(0), ANNOT_B);
assertHasTypeAnnots(ub.getComponents().get(1), ANNOT_A);
}
}
@ParameterizedTest
@EnumSource
void testTypeAnnotOnReceiver(SymImplementation impl) {
JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class);
/*
abstract void abOnReceiver(@A @B ClassWithTypeAnnotationsOnMethods this);
*/
{
JMethodSig t = getMethodType(sym, "abOnReceiver");
assertThat(t.getFormalParameters(), Matchers.empty());
assertHasTypeAnnots(t.getAnnotatedReceiverType(), ANNOTS_A_B);
}
}
}
| 6,759 | 37.409091 | 106 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTInitializerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTInitializerTest extends BaseParserTest {
@Test
void testDontCrashOnBlockStatement() {
java.parse("public class Foo { { x = 5; } }");
}
}
| 391 | 19.631579 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java20PreviewTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java20PreviewTreeDumpTest extends BaseTreeDumpTest {
private final JavaParsingHelper java20p =
JavaParsingHelper.DEFAULT.withDefaultVersion("20-preview")
.withResourceContext(Java20PreviewTreeDumpTest.class, "jdkversiontests/java20p/");
private final JavaParsingHelper java20 = java20p.withDefaultVersion("20");
Java20PreviewTreeDumpTest() {
super(new RelevantAttributePrinter(), ".java");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return java20p;
}
@Test
void dealingWithNullBeforeJava20Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java20.parseResource("DealingWithNull.java"));
assertTrue(thrown.getMessage().contains("Null in switch cases is a preview feature of JDK 20, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void dealingWithNull() {
doTest("DealingWithNull");
}
@Test
void enhancedTypeCheckingSwitch() {
doTest("EnhancedTypeCheckingSwitch");
}
@Test
void exhaustiveSwitch() {
doTest("ExhaustiveSwitch");
}
@Test
void guardedAndParenthesizedPatternsBeforeJava20Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java20.parseResource("GuardedAndParenthesizedPatterns.java"));
assertTrue(thrown.getMessage().contains("Patterns in switch statements is a preview feature of JDK 20, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void guardedAndParenthesizedPatterns() {
doTest("GuardedAndParenthesizedPatterns");
}
@Test
void patternsInSwitchLabelsBeforeJava20Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java20.parseResource("PatternsInSwitchLabels.java"));
assertTrue(thrown.getMessage().contains("Patterns in switch statements is a preview feature of JDK 20, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void patternsInSwitchLabels() {
doTest("PatternsInSwitchLabels");
}
@Test
void refiningPatternsInSwitch() {
doTest("RefiningPatternsInSwitch");
}
@Test
void scopeOfPatternVariableDeclarations() {
doTest("ScopeOfPatternVariableDeclarations");
}
@Test
void recordPatterns() {
doTest("RecordPatterns");
}
@Test
void recordPatternsBeforeJava20Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java20.parseResource("RecordPatterns.java"));
assertTrue(thrown.getMessage().contains("Deconstruction patterns is a preview feature of JDK 20, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void recordPatternsInEnhancedFor() {
doTest("RecordPatternsInEnhancedFor");
}
@Test
void recordPatternsInEnhancedForBeforeJava20Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java20.parseResource("RecordPatternsInEnhancedFor.java"));
assertTrue(thrown.getMessage().contains("Deconstruction patterns in enhanced for statement is a preview feature of JDK 20, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void recordPatternsExhaustiveSwitch() {
doTest("RecordPatternsExhaustiveSwitch");
}
}
| 4,266 | 35.161017 | 185 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTCompactConstructorDeclarationTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTCompactConstructorDeclarationTest extends BaseParserTest {
@Test
void compactConstructorWithLambda() {
ASTCompactConstructorDeclaration compactConstructor = java.getNodes(ASTCompactConstructorDeclaration.class,
"import java.util.Objects;"
+ "record RecordWithLambdaInCompactConstructor(String foo) {"
+ " RecordWithLambdaInCompactConstructor {"
+ " Objects.requireNonNull(foo, () -> \"foo\");"
+ " }"
+ "}")
.get(0);
assertEquals(1, compactConstructor.getBody().getNumChildren());
}
}
| 955 | 33.142857 | 115 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/EncodingTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class EncodingTest extends BaseParserTest {
@Test
void testDecodingOfUTF8() {
ASTCompilationUnit acu = java.parse("class Foo { void é() {} }");
String methodName = acu.descendants(ASTMethodDeclaration.class).firstOrThrow().getName();
assertEquals("é", methodName);
}
}
| 592 | 24.782609 | 97 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/AllJavaAstTreeDumpTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectClasses({
ParserCornersTest.class,
Java14TreeDumpTest.class,
Java15TreeDumpTest.class,
Java16TreeDumpTest.class,
Java17TreeDumpTest.class,
Java19PreviewTreeDumpTest.class,
Java20PreviewTreeDumpTest.class
})
class AllJavaAstTreeDumpTest {
}
| 511 | 21.26087 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchLabelTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class ASTSwitchLabelTest extends BaseParserTest {
private final JavaParsingHelper java = JavaParsingHelper.DEFAULT;
@Test
void testDefaultOff() {
List<ASTSwitchLabel> ops = java.getNodes(ASTSwitchLabel.class, "public class Foo {\n void bar() {\n switch (x) {\n case 1: y = 2;\n }\n }\n}");
assertFalse(ops.get(0).isDefault());
}
@Test
void testDefaultSet() {
@NonNull ASTSwitchStatement switchStmt = java.parse(SWITCH_WITH_DEFAULT).descendants(ASTSwitchStatement.class).firstOrThrow();
assertTrue(switchStmt.hasDefaultCase());
assertFalse(switchStmt.isExhaustiveEnumSwitch());
assertTrue(switchStmt.getBranches().firstOrThrow().getLabel().isDefault());
assertFalse(switchStmt.getBranches().get(1).getLabel().isDefault());
}
@Test
void testExhaustiveEnum() {
@NonNull ASTSwitchStatement switchStmt = java.parse(EXHAUSTIVE_ENUM).descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStmt.hasDefaultCase());
assertTrue(switchStmt.isExhaustiveEnumSwitch());
}
@Test
void testNotExhaustiveEnum() {
@NonNull ASTSwitchStatement switchStmt = java.parse(NOT_EXHAUSTIVE_ENUM).descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStmt.hasDefaultCase());
assertFalse(switchStmt.isExhaustiveEnumSwitch());
}
@Test
void testEnumWithDefault() {
@NonNull ASTSwitchStatement switchStmt = java.parse(ENUM_SWITCH_WITH_DEFAULT).descendants(ASTSwitchStatement.class).firstOrThrow();
assertTrue(switchStmt.hasDefaultCase());
assertFalse(switchStmt.isExhaustiveEnumSwitch());
}
private static final String SWITCH_WITH_DEFAULT =
"public class Foo {\n"
+ " void bar() {\n"
+ " switch (x) {\n"
+ " default: y = 2;\n"
+ " case 4: break;\n"
+ " }\n"
+ " }\n"
+ "}";
private static final String EXHAUSTIVE_ENUM =
"public class Foo {\n"
+ " void bar() {\n"
+ " enum LocalEnum { A, B, C } "
+ " var v = LocalEnum.A; "
+ " switch (v) {\n"
+ " case A: break;\n"
+ " case B: break;\n"
+ " case C: break;\n"
+ " }\n"
+ " }\n"
+ "}";
private static final String NOT_EXHAUSTIVE_ENUM =
"public class Foo {\n"
+ " void bar() {\n"
+ " enum LocalEnum { A, B, C } "
+ " var v = LocalEnum.A; "
+ " switch (v) {\n"
+ " case A: break;\n"
+ " // case B: break;\n"
+ " case C: break;\n"
+ " }\n"
+ " }\n"
+ "}";
private static final String ENUM_SWITCH_WITH_DEFAULT =
"public class Foo {\n"
+ " void bar() {\n"
+ " enum LocalEnum { A, B, C } "
+ " var v = LocalEnum.A; "
+ " switch (v) {\n"
+ " case A: break;\n"
+ " case C: break;\n"
+ " default: break;\n"
+ " }\n"
+ " }\n"
+ "}";
}
| 3,689 | 33.485981 | 155 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JDKVersionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class JDKVersionTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java3 = JavaParsingHelper.DEFAULT
.withDefaultVersion("1.3")
.withResourceContext(JDKVersionTest.class, "jdkversiontests/");
private final JavaParsingHelper java4 = java3.withDefaultVersion("1.4");
private final JavaParsingHelper java5 = java3.withDefaultVersion("1.5");
private final JavaParsingHelper java7 = java3.withDefaultVersion("1.7");
private final JavaParsingHelper java8 = java3.withDefaultVersion("1.8");
private final JavaParsingHelper java9 = java3.withDefaultVersion("9");
// enum keyword/identifier
@Test
void testEnumAsKeywordShouldFailWith14() {
assertThrows(ParseException.class, () -> java5.parseResource("jdk14_enum.java"));
}
@Test
void testEnumAsIdentifierShouldPassWith14() {
java4.parseResource("jdk14_enum.java");
}
@Test
void testEnumAsKeywordShouldPassWith15() {
java5.parseResource("jdk15_enum.java");
}
@Test
void testEnumAsIdentifierShouldFailWith15() {
assertThrows(ParseException.class, () -> java5.parseResource("jdk14_enum.java"));
}
// enum keyword/identifier
// assert keyword/identifier
@Test
void testAssertAsKeywordVariantsSucceedWith14() {
java4.parseResource("assert_test1.java");
java4.parseResource("assert_test2.java");
java4.parseResource("assert_test3.java");
java4.parseResource("assert_test4.java");
}
@Test
void testAssertAsVariableDeclIdentifierFailsWith14() {
assertThrows(ParseException.class, () -> java4.parseResource("assert_test5.java"));
}
@Test
void testAssertAsMethodNameIdentifierFailsWith14() {
assertThrows(ParseException.class, () -> java4.parseResource("assert_test7.java"));
}
@Test
void testAssertAsIdentifierSucceedsWith13() {
java3.parseResource("assert_test5.java");
}
@Test
void testAssertAsKeywordFailsWith13() {
assertThrows(ParseException.class, () -> java3.parseResource("assert_test6.java"));
}
// assert keyword/identifier
@Test
void testVarargsShouldPassWith15() {
java5.parseResource("jdk15_varargs.java");
}
@Test
void testGenericCtorCalls() {
java5.parseResource("java5/generic_ctors.java");
}
@Test
void testGenericSuperCtorCalls() {
java5.parseResource("java5/generic_super_ctor.java");
}
@Test
void testAnnotArrayInitializer() {
java5.parseResource("java5/annotation_array_init.java");
}
@Test
void testVarargsShouldFailWith14() {
assertThrows(ParseException.class, () -> java4.parseResource("jdk15_varargs.java"));
}
@Test
void testJDK15ForLoopSyntaxShouldPassWith15() {
java5.parseResource("jdk15_forloop.java");
}
@Test
void testJDK15ForLoopSyntaxWithModifiers() {
java5.parseResource("jdk15_forloop_with_modifier.java");
}
@Test
void testJDK15ForLoopShouldFailWith14() {
assertThrows(ParseException.class, () -> java4.parseResource("jdk15_forloop.java"));
}
@Test
void testJDK15GenericsSyntaxShouldPassWith15() {
java5.parseResource("jdk15_generics.java");
}
@Test
void testVariousParserBugs() {
java5.parseResource("fields_bug.java");
java5.parseResource("gt_bug.java");
java5.parseResource("annotations_bug.java");
java5.parseResource("constant_field_in_annotation_bug.java");
java5.parseResource("generic_in_field.java");
}
@Test
void testNestedClassInMethodBug() {
java5.parseResource("inner_bug.java");
java5.parseResource("inner_bug2.java");
}
@Test
void testGenericsInMethodCall() {
java5.parseResource("generic_in_method_call.java");
}
@Test
void testGenericINAnnotation() {
java5.parseResource("generic_in_annotation.java");
}
@Test
void testGenericReturnType() {
java5.parseResource("generic_return_type.java");
}
@Test
void testMultipleGenerics() {
// See java/lang/concurrent/CopyOnWriteArraySet
java5.parseResource("funky_generics.java");
// See java/lang/concurrent/ConcurrentHashMap
java5.parseResource("multiple_generics.java");
}
@Test
void testAnnotatedParams() {
java5.parseResource("annotated_params.java");
}
@Test
void testAnnotatedLocals() {
java5.parseResource("annotated_locals.java");
}
@Test
void testAssertAsIdentifierSucceedsWith13Test2() {
java3.parseResource("assert_test5_a.java");
}
@Test
void testBinaryAndUnderscoresInNumericalLiterals() {
java7.parseResource("jdk17_numerical_literals.java");
}
@Test
void testStringInSwitch() {
java7.parseResource("jdk17_string_in_switch.java");
}
@Test
void testGenericDiamond() {
java7.parseResource("jdk17_generic_diamond.java");
}
@Test
void testTryWithResources() {
java7.parseResource("jdk17_try_with_resources.java");
}
@Test
void testTryWithResourcesSemi() {
java7.parseResource("jdk17_try_with_resources_semi.java");
}
@Test
void testTryWithResourcesMulti() {
java7.parseResource("jdk17_try_with_resources_multi.java");
}
@Test
void testTryWithResourcesWithAnnotations() {
java7.parseResource("jdk17_try_with_resources_with_annotations.java");
}
@Test
void testMulticatch() {
java7.parseResource("jdk17_multicatch.java");
}
@Test
void testMulticatchWithAnnotations() {
java7.parseResource("jdk17_multicatch_with_annotations.java");
}
@Test
void jdk9PrivateInterfaceMethodsInJava18() {
assertThrows(ParseException.class, () -> java8.parseResource("java9/jdk9_private_interface_methods.java"));
}
@Test
void testPrivateMethods() {
java8.parse("public class Foo { private void bar() { } }");
}
@Test
void testTypeAnnotations() {
java8.parseResource("java8/type_annotations.java");
}
@Test
void testNestedPrivateMethods() {
java8.parse("public interface Baz { public static class Foo { private void bar() { } } }");
}
@Test
void jdk9PrivateInterfaceMethods() {
java9.parseResource("java9/jdk9_private_interface_methods.java");
}
@Test
void jdk9InvalidIdentifierInJava18() {
java8.parseResource("java9/jdk9_invalid_identifier.java");
}
@Test
void jdk9InvalidIdentifier() {
assertThrows(ParseException.class, () -> java9.parseResource("java9/jdk9_invalid_identifier.java"));
}
@Test
void jdk9AnonymousDiamondInJava8() {
assertThrows(ParseException.class, () -> java8.parseResource("java9/jdk9_anonymous_diamond.java"));
}
@Test
void jdk9AnonymousDiamond() {
java9.parseResource("java9/jdk9_anonymous_diamond.java");
}
@Test
void jdk9ModuleInfoInJava8() {
assertThrows(ParseException.class, () -> java8.parseResource("java9/jdk9_module_info.java"));
}
@Test
void jdk9ModuleInfo() {
java9.parseResource("java9/jdk9_module_info.java");
}
@Test
void testAnnotatedModule() {
java9.parseResource("java9/jdk9_module_info_with_annot.java");
}
@Test
void jdk9TryWithResourcesInJava8() {
assertThrows(ParseException.class, () -> java8.parseResource("java9/jdk9_try_with_resources.java"));
}
@Test
void jdk9TryWithResources() {
java9.parseResource("java9/jdk9_try_with_resources.java");
}
@Test
void jdk7PrivateMethodInnerClassInterface1() {
ASTCompilationUnit acu = java7.parseResource("private_method_in_inner_class_interface1.java");
List<ASTMethodDeclaration> methods = acu.findDescendantsOfType(ASTMethodDeclaration.class, true);
assertEquals(3, methods.size());
for (ASTMethodDeclaration method : methods) {
assertFalse(method.getEnclosingType().isInterface());
}
}
@Test
void jdk7PrivateMethodInnerClassInterface2() {
ParseException thrown = assertThrows(ParseException.class, () -> java7.parseResource("private_method_in_inner_class_interface2.java"));
assertThat(thrown.getMessage(), containsString("line 19"));
}
@Override
public @NonNull BaseParsingHelper<?, ?> getParser() {
return java9;
}
}
| 9,319 | 28.034268 | 143 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java14TreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
/**
* Tests new java14 standard features.
*/
class Java14TreeDumpTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java14 =
JavaParsingHelper.DEFAULT.withDefaultVersion("14")
.withResourceContext(Java14TreeDumpTest.class, "jdkversiontests/java14/");
private final JavaParsingHelper java13 = java14.withDefaultVersion("13");
@Override
public @NonNull BaseParsingHelper<?, ?> getParser() {
return java14;
}
/**
* Tests switch expressions with yield.
*/
@Test
void switchExpressions() {
doTest("SwitchExpressions");
}
/**
* In java13, switch expressions are only available with preview.
*/
@Test
void switchExpressions13ShouldFail() {
assertThrows(ParseException.class, () -> java13.parseResource("SwitchExpressions.java"));
}
@Test
void checkYieldConditionalBehaviour() {
doTest("YieldStatements");
}
@Test
void multipleCaseLabels() {
doTest("MultipleCaseLabels");
}
@Test
void switchRules() {
doTest("SwitchRules");
}
@Test
void simpleSwitchExpressions() {
doTest("SimpleSwitchExpressions");
}
}
| 1,760 | 23.802817 | 107 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/CommentTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class CommentTest extends BaseParserTest {
@Test
void testMultiLinesInSingleLine() {
String comment = "/* single line. */";
String filtered = filter(comment);
assertEquals(1, lineCount(filtered));
assertEquals("single line.", filtered);
}
@Test
void testMultiLinesInSingleLineSimple() {
String comment = "// single line.";
String filtered = filter(comment);
assertEquals(1, lineCount(filtered));
assertEquals("single line.", filtered);
}
@Test
void testMultiLinesInSingleLineFormal() {
String comment = "/** single line. */";
String filtered = filter(comment);
assertEquals(1, lineCount(filtered));
assertEquals("single line.", filtered);
}
@Test
void testMultiLinesInMultiLine() {
String comment =
"/*\n"
+ " * line 1\n"
+ " * line 2\n"
+ " */\n";
String filtered = filter(comment);
assertEquals(2, lineCount(filtered));
assertEquals("line 1\nline 2", filtered);
}
@Test
void testMultiLinesInMultiLineCrLf() {
String comment =
"/*\r\n"
+ " * line 1\r\n"
+ " * line 2\r\n"
+ " */\r\n";
String filtered = filter(comment);
assertEquals(2, lineCount(filtered));
assertEquals("line 1\nline 2", filtered);
}
@Test
void testMultiLinesInMultiLineFormal() {
String comment =
"/**\n"
+ " * line 1\n"
+ " * line 2\n"
+ " */\n";
String filtered = filter(comment);
assertEquals(2, lineCount(filtered));
assertEquals("line 1\nline 2", filtered);
}
@Test
void testMultiLinesInMultiLineFormalCrLf() {
String comment =
"/**\r\n"
+ " * line 1\r\n"
+ " * line 2\r\n"
+ " */\r\n";
String filtered = filter(comment);
assertEquals(2, lineCount(filtered));
assertEquals("line 1\nline 2", filtered);
}
@Test
void testMultiLinesInMultiLineNoAsteriskEmpty() {
String comment =
"/**\n"
+ " * line 1\n"
+ "line 2\n"
+ "\n"
+ " */\n";
String filtered = filter(comment);
assertEquals(2, lineCount(filtered));
assertEquals("line 1\nline 2", filtered);
}
private String filter(String comment) {
JavaComment firstComment = java.parse(comment).getComments().get(0);
return StringUtils.join(firstComment.getFilteredLines(), '\n');
}
private int lineCount(String filtered) {
return StringUtils.countMatches(filtered, '\n') + 1;
}
}
| 3,174 | 28.12844 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java15TreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java15TreeDumpTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java15 =
JavaParsingHelper.DEFAULT.withDefaultVersion("15")
.withResourceContext(Java15TreeDumpTest.class, "jdkversiontests/java15/");
private final JavaParsingHelper java14 = java15.withDefaultVersion("14");
@Override
public BaseParsingHelper<?, ?> getParser() {
return java15;
}
@Test
void textBlocks() {
doTest("TextBlocks");
}
@Test
void textBlocksBeforeJava15ShouldFail() {
assertThrows(ParseException.class, () -> java14.parseResource("TextBlocks.java"));
}
@Test
void stringEscapeSequenceShouldFail() {
assertThrows(ParseException.class, () -> java14.parse("class Foo { String s =\"a\\sb\"; }"));
}
@Test
void sealedAndNonSealedIdentifiers() {
doTest("NonSealedIdentifier");
}
}
| 1,394 | 28.680851 | 111 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/TextBlockEscapeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static net.sourceforge.pmd.lang.java.ast.ASTStringLiteral.determineTextBlockContent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.util.StringUtil;
class TextBlockEscapeTest extends BaseParserTest {
@Test
void testStringEscapes() {
testStringEscape("abcd", "abcd");
testStringEscape("abcd\\f", "abcd\f");
testStringEscape("abcd\\n", "abcd\n");
testStringEscape("abcd\\t", "abcd\t");
testStringEscape("abcd\\bx", "abcd\bx");
testStringEscape("abcd\\'x", "abcd\'x");
// note that this one is actually invalid syntax
testStringEscape("abcd\\", "abcd\\");
testStringEscape("abcd\\\\", "abcd\\");
}
@Test
void testStringOctalEscapes() {
testStringEscape("\\0123", "\0123");
testStringEscape("\\01ab", "\01ab");
testStringEscape("\\0", "\0");
}
@Test
void testStringUnknownEscape() {
testStringEscape("\\x", "\\x");
}
// note the argument order
private void testStringEscape(String actual, String expected) {
actual = StringUtil.inDoubleQuotes(actual);
assertEquals(expected,
ASTStringLiteral.determineStringContent(Chars.wrap(actual)));
}
@Test
void testTextBlockContent() {
assertEquals("winter", determineTextBlockContent("\"\"\"\n winter\"\"\""),
"single line text block");
assertEquals("winter\n", determineTextBlockContent("\"\"\"\n"
+ " winter\n"
+ " \"\"\""),
"single line text block with LF");
assertEquals(" winter\n", determineTextBlockContent("\"\"\"\n"
+ " winter\n"
+ " \"\"\""),
"single line text block with LF, some indent preserved");
}
@Test
void emptyTextBlock() {
assertEquals("",
determineTextBlockContent("\"\"\"\n \"\"\""),
"empty text block");
}
@Test
void testEscapeBlockDelimiter() {
assertEquals("String text = \"\"\"\n"
+ " A text block inside a text block\n"
+ "\"\"\";\n",
determineTextBlockContent("\"\"\"\n"
+ " String text = \\\"\"\"\n"
+ " A text block inside a text block\n"
+ " \\\"\"\";\n"
+ " \"\"\""),
"escaped text block in inside text block");
}
@Test
void testCrEscape() {
assertEquals("<html>\r\n"
+ " <body>\r\n"
+ " <p>Hello, world</p>\r\n"
+ " </body>\r\n"
+ "</html>\r\n",
determineTextBlockContent("\"\"\"\n"
+ " <html>\\r\n"
+ " <body>\\r\n"
+ " <p>Hello, world</p>\\r\n"
+ " </body>\\r\n"
+ " </html>\\r\n"
+ " \"\"\""),
"text block with escapes");
}
@Test
void testBasicHtmlBlock() {
assertEquals("<html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ "</html>\n",
determineTextBlockContent("\"\"\"\n"
+ " <html> \n"
+ " <body>\n"
+ " <p>Hello, world</p> \n"
+ " </body> \n"
+ " </html> \n"
+ " \"\"\""),
"basic text block example with html");
}
@Test
void testLineContinuation() {
assertEquals("Lorem ipsum dolor sit amet, consectetur adipiscing "
+ "elit, sed do eiusmod tempor incididunt ut labore "
+ "et dolore magna aliqua.",
determineTextBlockContent("\"\"\"\n"
+ " Lorem ipsum dolor sit amet, consectetur adipiscing \\\n"
+ " elit, sed do eiusmod tempor incididunt ut labore \\\n"
+ " et dolore magna aliqua.\\\n"
+ " \"\"\""),
"new escape: line continuation");
}
@Test
void testEscapeSpace() {
assertEquals("red \n"
+ "green \n"
+ "blue \n",
determineTextBlockContent("\"\"\"\n"
+ " red \\s\n"
+ " green\\s\n"
+ " blue \\s\n"
+ " \"\"\""),
"new escape: space escape");
}
@Test
void testLineEndingNormalization() {
assertEquals("<html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ "</html>\n",
determineTextBlockContent("\"\"\"\r\n"
+ " <html> \r\n"
+ " <body>\r\n"
+ " <p>Hello, world</p> \r\n"
+ " </body> \r\n"
+ " </html> \r\n"
+ " \"\"\""),
"with crlf line endings");
assertEquals("<html>\n"
+ " <body>\n"
+ " <p>Hello, world</p>\n"
+ " </body>\n"
+ "</html>\n",
determineTextBlockContent("\"\"\"\r"
+ " <html> \r"
+ " <body>\r"
+ " <p>Hello, world</p> \r"
+ " </body> \r"
+ " </html> \r"
+ " \"\"\""),
"with cr line endings");
}
@Test
void testEmptyLines() {
assertEquals("\ntest\n", determineTextBlockContent("\"\"\"\n"
+ " \n"
+ " test\n"
+ " \"\"\""),
"empty line directly after opening");
assertEquals("\ntest\n", determineTextBlockContent("\"\"\"\r\n"
+ " \r\n"
+ " test\r\n"
+ " \"\"\""),
"empty crlf line directly after opening");
assertEquals("\ntest\n", determineTextBlockContent("\"\"\"\n"
+ "\n"
+ "test\n"
+ "\"\"\""),
"empty line directly after opening without indentation");
assertEquals("\ntest\n", determineTextBlockContent("\"\"\"\r\n"
+ "\r\n"
+ "test\r\n"
+ "\"\"\""),
"empty crlf line directly after opening without indentation");
}
@Test
void testTextBlockWithBackslashEscape() {
assertEquals("\\test\n",
determineTextBlockContent("\"\"\"\n \\\\test\n \"\"\""),
"text block with backslash escape");
}
}
| 9,923 | 46.711538 | 112 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java17TreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java17TreeDumpTest extends BaseTreeDumpTest {
private final JavaParsingHelper java17 =
JavaParsingHelper.DEFAULT.withDefaultVersion("17")
.withResourceContext(Java17TreeDumpTest.class, "jdkversiontests/java17/");
private final JavaParsingHelper java16 = java17.withDefaultVersion("16");
Java17TreeDumpTest() {
super(new RelevantAttributePrinter(), ".java");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return java17;
}
@Test
void sealedClassBeforeJava17() {
ParseException thrown = assertThrows(ParseException.class, () -> java16.parseResource("geometry/Shape.java"));
assertTrue(thrown.getMessage().contains("Sealed classes are a feature of Java 17, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void sealedClass() {
doTest("geometry/Shape");
}
@Test
void nonSealedClass() {
doTest("geometry/Square");
}
@Test
void sealedQualifiedPermitClass() {
doTest("SealedInnerClasses");
}
@Test
void sealedInterfaceBeforeJava17() {
ParseException thrown = assertThrows(ParseException.class, () -> java16.parseResource("expression/Expr.java"));
assertTrue(thrown.getMessage().contains("Sealed classes are a feature of Java 17, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void sealedInterface() {
doTest("expression/Expr");
}
@Test
void localVars() {
doTest("LocalVars");
}
}
| 2,287 | 30.777778 | 144 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java16TreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static net.sourceforge.pmd.lang.java.types.TestUtilitiesForTypesKt.hasType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.symbols.JElementSymbol;
import net.sourceforge.pmd.lang.java.types.JPrimitiveType;
class Java16TreeDumpTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java16 =
JavaParsingHelper.DEFAULT.withDefaultVersion("16")
.withResourceContext(Java16TreeDumpTest.class, "jdkversiontests/java16/");
private final JavaParsingHelper java15 = java16.withDefaultVersion("15");
@Override
public BaseParsingHelper<?, ?> getParser() {
return java16;
}
@Test
void patternMatchingInstanceof() {
doTest("PatternMatchingInstanceof");
// extended tests for type resolution etc.
ASTCompilationUnit ast = java16.parseResource("PatternMatchingInstanceof.java");
NodeStream<ASTTypePattern> patterns = ast.descendants(ASTTypePattern.class);
assertThat(patterns.toList(), not(empty()));
for (ASTTypePattern expr : patterns) {
assertThat(expr.getVarId(), hasType(String.class));
}
}
@Test
void patternMatchingInstanceofBeforeJava16ShouldFail() {
assertThrows(ParseException.class, () -> java15.parseResource("PatternMatchingInstanceof.java"));
}
@Test
void localClassAndInterfaceDeclarations() {
doTest("LocalClassAndInterfaceDeclarations");
}
@Test
void localClassAndInterfaceDeclarationsBeforeJava16ShouldFail() {
assertThrows(ParseException.class, () -> java15.parseResource("LocalClassAndInterfaceDeclarations.java"));
}
@Test
void localAnnotationsAreNotAllowed() {
assertThrows(ParseException.class, () -> java16.parse("public class Foo { { @interface MyLocalAnnotation {} } }"));
}
@Test
void localRecords() {
doTest("LocalRecords");
}
@Test
void recordPoint() {
doTest("Point");
// extended tests for type resolution etc.
ASTCompilationUnit compilationUnit = java16.parseResource("Point.java");
ASTRecordDeclaration recordDecl = compilationUnit.descendants(ASTRecordDeclaration.class).first();
List<ASTRecordComponent> components = recordDecl.descendants(ASTRecordComponentList.class)
.children(ASTRecordComponent.class).toList();
ASTVariableDeclaratorId varId = components.get(0).getVarId();
JElementSymbol symbol = varId.getSymbol();
assertEquals("x", symbol.getSimpleName());
assertTrue(varId.getTypeMirror().isPrimitive(JPrimitiveType.PrimitiveTypeKind.INT));
}
@Test
void recordPointBeforeJava16ShouldFail() {
assertThrows(ParseException.class, () -> java15.parseResource("Point.java"));
}
@Test
void recordCtorWithThrowsShouldFail() {
assertThrows(ParseException.class, () -> java16.parse(" record R {"
+ " R throws IOException {}"
+ " }"));
}
@Test
void recordMustNotExtend() {
assertThrows(ParseException.class, () -> java16.parse("record RecordEx(int x) extends Number { }"));
}
@Test
void innerRecords() {
doTest("Records");
}
@Test
void recordIsARestrictedIdentifier() {
assertThrows(ParseException.class, () -> java16.parse("public class record {}"));
}
@Test
void sealedAndNonSealedIdentifiers() {
doTest("NonSealedIdentifier");
}
}
| 4,281 | 32.716535 | 123 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/CommentAssignmentTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class CommentAssignmentTest extends BaseParserTest {
/**
* Blank lines in comments should not raise an exception. See bug #1048.
*/
@Test
void testFilteredCommentIn() {
ASTCompilationUnit node = java.parse("public class Foo {\n"
+ " /* multi line comment with blank lines\n\n\n */\n"
+ " /** a formal comment with blank lines\n\n\n */"
+ "}");
JavaComment comment = node.getComments().get(0);
assertFalse(comment.isSingleLine());
assertFalse(comment.hasJavadocContent());
assertEquals("multi line comment with blank lines", StringUtils.join(comment.getFilteredLines(), ' '));
comment = node.getComments().get(1);
assertFalse(comment.isSingleLine());
assertTrue(comment.hasJavadocContent());
assertThat(comment, instanceOf(JavadocComment.class));
assertEquals("a formal comment with blank lines", StringUtils.join(comment.getFilteredLines(), ' '));
}
@Test
void testCommentAssignments() {
ASTCompilationUnit node = java.parse("public class Foo {\n"
+ " /** Comment 1 */\n"
+ " public void method1() {}\n"
+ " \n"
+ " /** Comment 2 */\n"
+ " \n"
+ " /** Comment 3 */\n"
+ " public void method2() {}" + "}");
List<ASTMethodDeclaration> methods = node.descendants(ASTMethodDeclaration.class).toList();
assertCommentEquals(methods.get(0), "/** Comment 1 */");
assertCommentEquals(methods.get(1), "/** Comment 3 */");
}
@Test
void testCommentAssignmentsWithAnnotation() {
ASTCompilationUnit node = java.parse("public class Foo {\n"
+ " /** Comment 1 */\n"
+ " @Oha public void method1() {}\n"
+ " \n"
+ " /** Comment 2 */\n"
+ " @Oha\n"
// note that since this is the first token, the prev comment gets selected
+ " /** Comment 3 */\n"
+ " public void method2() {}" + "}");
List<ASTMethodDeclaration> methods = node.descendants(ASTMethodDeclaration.class).toList();
assertCommentEquals(methods.get(0), "/** Comment 1 */");
assertCommentEquals(methods.get(1), "/** Comment 2 */");
}
@Test
void testCommentAssignmentOnPackage() {
ASTCompilationUnit node = java.parse("/** Comment 1 */\n"
+ "package bar;\n");
assertCommentEquals(node.descendants(ASTPackageDeclaration.class).firstOrThrow(),
"/** Comment 1 */");
}
@Test
void testCommentAssignmentOnClass() {
ASTCompilationUnit node = java.parse("/** outer */\n"
+ "class Foo { "
+ " /** inner */ class Nested { } "
+ " { /** local */ class Local {}} "
+ " /** enum */enum NestedEnum {}"
+ "}");
List<ASTAnyTypeDeclaration> types = node.descendants(ASTAnyTypeDeclaration.class).crossFindBoundaries().toList();
assertCommentEquals(types.get(0), "/** outer */");
assertCommentEquals(types.get(1), "/** inner */");
assertCommentEquals(types.get(2), "/** local */");
assertCommentEquals(types.get(3), "/** enum */");
}
@Test
void testCommentAssignmentOnEnum() {
ASTCompilationUnit node = java.parse("enum Foo { "
+ " /** A */ A,"
+ " /** B */ @Oha B,"
+ " C,"
+ " /* not javadoc */ D,"
+ "}");
List<ASTEnumConstant> constants = node.descendants(ASTEnumConstant.class).toList();
assertCommentEquals(constants.get(0), "/** A */");
assertCommentEquals(constants.get(1), "/** B */");
assertHasNoComment(constants.get(2));
assertHasNoComment(constants.get(3));
}
private void assertCommentEquals(JavadocCommentOwner pack, String expected) {
assertNotNull(pack.getJavadocComment(), "null comment on " + pack);
assertEquals(expected, pack.getJavadocComment().getText().toString());
}
private void assertHasNoComment(JavadocCommentOwner pack) {
assertNull(pack.getJavadocComment(), "Expected null comment on " + pack);
}
}
| 6,087 | 43.437956 | 123 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ConstantExpressionsTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ConstantExpressionsTests extends BaseParserTest {
private Executable isConst(String expr, Object value) {
return () -> {
ASTExpression e = parseExpr(expr);
assertEquals(value, e.getConstValue(), "Constant value of '" + expr + "'");
};
}
private Executable notConst(String expr) {
return isConst(expr, null);
}
@Test
void testUnaries() {
assertAll(
isConst("+1", 1),
isConst("+1L", 1L),
isConst("-1L", -1L),
isConst("-1D", -1D),
isConst("-4f", -4f),
isConst("~1", ~1),
isConst("+ 'c'", (int) 'c'),
isConst("- 'c'", -(int) 'c'),
isConst("! true", false),
isConst("! false", true),
isConst("!!! false", true),
// those are type errors
notConst("- true"),
notConst("~ true"),
notConst("~ 1.0"),
notConst("+ \"\"")
);
}
@Test
void testCasts() {
assertAll(
isConst("+1", 1),
isConst("(long) +1", 1L),
isConst("(long) 'c'", (long) 'c'),
isConst("(byte) 'c'", (byte) 'c'),
isConst("(char) 1", (char) 1),
isConst("(float) 1d", 1f),
isConst("(double) 2f", 2d),
isConst("(int) 2f", 2),
isConst("(short) 2f", (short) 2f),
isConst("(long) 2f", 2L),
// those are type errors
notConst("(Object) 1"),
notConst("(String) null"),
notConst("(char) null"),
notConst("(int) new Integer(0)")
);
}
@Test
void testShortcutBoolean() {
assertAll(
isConst("true && true", true),
isConst("true && false", false),
isConst("false && true", false),
isConst("false && false", false),
isConst("true || true", true),
isConst("true || false", true),
isConst("false || true", true),
isConst("false || false", false),
isConst("false || (false ? false: true)", true),
// those are type errors
notConst("1 && true"),
notConst("true && 1"),
notConst("true && \"\""),
notConst("\"\" && true"),
notConst("1 || true"),
notConst("true || 1"),
notConst("true || \"\""),
notConst("\"\" || true")
);
}
@Test
strictfp void testBitwise() {
assertAll(
isConst("~1 ^ ~8", ~1 ^ ~8),
isConst("~1 ^ ~8L", ~1 ^ ~8L),
isConst("1L ^ 0", 1L),
isConst("true ^ true", false),
isConst("true ^ false", true),
isConst("false ^ true", true),
isConst("false ^ false", false),
isConst("1 & 1", 1),
isConst("1 & 0L", 0L),
isConst("1L & 0", 0L),
isConst("true & true", true),
isConst("true & false", false),
isConst("false & true", false),
isConst("false & false", false),
isConst("1 | 1", 1),
isConst("12L | 0", 12L),
isConst("9L | 0", 9L),
isConst("true | true", true),
isConst("true | false", true),
isConst("false | true", true),
isConst("false | false", false),
notConst("false | \"\""),
notConst("1 | 1.0"),
notConst("1 & 1.0f"),
notConst("false | 0"),
notConst("false ^ 0"),
notConst("false & 0")
);
}
@Test
void testShifts() {
assertAll(
isConst("1 << 2", 1 << 2),
isConst("1 << 2L", 1 << 2L),
isConst("1L << 2L", 1L << 2L),
isConst("1L << 2", 1L << 2),
isConst("8 >> 2", 8 >> 2),
isConst("8 >> 2L", 8 >> 2L),
isConst("8L >> 2L", 8L >> 2L),
isConst("8L >> 2", 8L >> 2),
isConst("8 >>> 2", 8 >>> 2),
isConst("8 >>> 2L", 8 >>> 2L),
isConst("8L >>> 2L", 8L >>> 2L),
isConst("8L >>> 2", 8L >>> 2),
// those are type errors
notConst("1 << 2d"),
notConst("1 >> 2d"),
notConst("1 >>> 2d"),
notConst("1d << 2"),
notConst("1d >> 2"),
notConst("1d >>> 2")
);
}
@Test
void testAdditives() {
assertAll(
isConst("1 + 2", 3),
isConst("1 + ~2", 1 + ~2),
isConst("1 - 2", -1),
isConst("1 - -2d", 3d),
isConst("1 - 2 - 1f", -2f),
isConst("1 - (2 - 1L)", 0L),
isConst("1 + -2d", -1d),
isConst("1 - (2 + 1f)", -2f),
isConst("1 + (2 - 1L)", 2L),
// concat
isConst("1 + \"xx\"", "1xx"),
isConst("\"xx\" + 1", "xx1"),
isConst("1 + 2 + \"xx\"", "3xx"),
isConst("1 + (2 + \"xx\")", "12xx"),
isConst("1 + \"xx\" + 2", "1xx2"),
isConst("1 + (\"xx\" + 2)", "1xx2"),
// those are type errors
notConst("1+true"),
notConst("1-true"),
notConst("1-\"\"")
);
}
@Test
strictfp void testMult() {
assertAll(
isConst("1 * 2.0", 1 * 2.0),
isConst("1L * 2", 2L),
isConst("1L * 2F", 1L * 2F),
isConst("1 * 2F", 1 * 2F),
isConst("1 * 2", 2),
isConst("40 / 4", 40 / 4),
isConst("40 / 4.0", 40 / 4.0),
isConst("40 / 4L", 40 / 4L),
isConst("40 / 4.0f", 40 / 4.0f),
isConst("40 / 4.0f", 40 / 4.0f),
isConst("40 % 4", 40 % 4),
isConst("40 % 4.0", 40 % 4.0),
isConst("40 % 4L", 40 % 4L),
isConst("40 % 4.0f", 40 % 4.0f),
isConst("40 % 4.0f", 40 % 4.0f),
isConst("3.0f % 4.0d", 3.0 % 4.0d),
// those are type errors
notConst("1*true"),
notConst("true*1"),
notConst("true/1"),
notConst("\"\"/1"),
notConst("1/true"),
notConst("1/\"\""),
notConst("true%1"),
notConst("\"\"%1"),
notConst("1%true"),
notConst("1%\"\"")
);
}
@Test
strictfp void testRelationals() {
assertAll(
isConst("1 <= 2L", true),
isConst("2 <= 2d", true),
isConst("'c' <= 6", false),
isConst("4 <= 2d", false),
isConst("4f <= 2", false),
isConst("1 > 2L", false),
isConst("2 > 2d", false),
isConst("'c' > 6", true),
isConst("4 > 2d", true),
isConst("4f > 2", true),
isConst("1 < 2L", true),
isConst("2 < 2d", false),
isConst("'c' < 6", false),
isConst("4 < 2d", false),
isConst("4f < 2", false),
isConst("1 >= 2L", false),
isConst("2 >= 2d", true),
isConst("'c' >= 6", true),
isConst("4 >= 2d", true),
isConst("4f >= 2", true),
notConst("\"\" instanceof String"),
notConst("\"\" <= 3"),
notConst("4 <= \"\""),
notConst("4 < \"\""),
notConst("\"\" < 3"),
notConst("4 > \"\""),
notConst("\"\" > 3"),
notConst("4 >= \"\""),
notConst("\"\" >= 3")
);
}
@Test
strictfp void testEquality() {
assertAll(
isConst("1 == 2", false),
isConst("2 != 2d", false),
isConst("'x' != (int) 'x'", false),
isConst("'x' == (int) 'x'", true),
notConst("\"\" == \"\""),
notConst("\"\" != \"\""),
notConst("2 != \"\"")
);
}
@Test
strictfp void testConditionals() {
assertAll(
isConst("true ? 1 + 2 : 4", 3),
isConst("false ? 1 + 2 : 4", 4),
isConst("1 == 2 ? 1 + 2 : 4", 4),
isConst("1 < 2 ? 1 + 2 : 4", 3),
notConst("false ? 1 + 2 : null"),
notConst("false ? null : 5"),
notConst("false ? (Integer) 1 + 2 : 5"),
notConst("(Boolean) false ? 1 + 2 : 5")
);
}
@Test
strictfp void testConstFields() {
assertAll(
isConst("Math.PI", Math.PI),
isConst("Math.PI > 3", true),
notConst("System.out")
);
}
}
| 9,030 | 26.366667 | 87 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaCommentTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.java.BaseParserTest;
/**
* @author Clément Fournier
*/
class JavaCommentTest extends BaseParserTest {
@Test
void testFilteredLines() {
JavaComment comment = parseComment(
"/**\n"
+ " * @author Clément Fournier\n"
+ " *"
+ " */\n"
);
assertThat(comment.getFilteredLines(),
contains(Chars.wrap("@author Clément Fournier")));
}
@Test
void testFilteredLinesKeepBlankLines() {
JavaComment comment = parseComment(
"/**\n"
+ " * @author Clément Fournier\n"
+ " *"
+ " */\n"
);
assertThat(comment.getFilteredLines(true),
contains(Chars.wrap(""), Chars.wrap("@author Clément Fournier"), Chars.wrap("")));
}
JavaComment parseComment(String text) {
ASTCompilationUnit parsed = java.parse(text);
return JavaComment.getLeadingComments(parsed).findFirst().get();
}
@Test
void getLeadingComments() {
ASTCompilationUnit parsed = java.parse("/** a */ class Fooo { /** b */ int field; }");
List<JavadocCommentOwner> docCommentOwners = parsed.descendants(JavadocCommentOwner.class).toList();
checkCommentMatches(docCommentOwners.get(0), "/** a */");
checkCommentMatches(docCommentOwners.get(1), "/** b */");
}
private static void checkCommentMatches(JavadocCommentOwner commentOwner, String expectedText) {
// this is preassigned by the comment assignment pass
JavadocComment comment = commentOwner.getJavadocComment();
assertEquals(expectedText, comment.getText().toString());
// this is fetched adhoc
List<JavaComment> collected = JavaComment.getLeadingComments(commentOwner).collect(Collectors.toList());
assertEquals(listOf(comment), collected);
}
}
| 2,434 | 30.623377 | 112 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTVariableDeclaratorIdTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil;
class ASTVariableDeclaratorIdTest extends BaseParserTest {
@Test
void testIsExceptionBlockParameter() {
ASTCompilationUnit acu = java.parse(EXCEPTION_PARAMETER);
ASTVariableDeclaratorId id = acu.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
assertTrue(id.isExceptionBlockParameter());
}
@Test
void testTypeNameNode() {
ASTCompilationUnit acu = java.parse(TYPE_NAME_NODE);
ASTVariableDeclaratorId id = acu.findDescendantsOfType(ASTVariableDeclaratorId.class).get(0);
ASTClassOrInterfaceType name = (ASTClassOrInterfaceType) id.getTypeNameNode();
assertEquals("String", name.getSimpleName());
}
@Test
void testAnnotations() {
ASTCompilationUnit acu = java.parse(TEST_ANNOTATIONS);
ASTVariableDeclaratorId id = acu.findDescendantsOfType(ASTVariableDeclaratorId.class).get(0);
ASTClassOrInterfaceType name = (ASTClassOrInterfaceType) id.getTypeNode();
assertEquals("String", name.getSimpleName());
}
@Test
void testLambdaWithType() throws Exception {
ASTCompilationUnit acu = java8.parse(TEST_LAMBDA_WITH_TYPE);
ASTLambdaExpression lambda = acu.getFirstDescendantOfType(ASTLambdaExpression.class);
ASTVariableDeclaratorId f = lambda.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
assertEquals("File", PrettyPrintingUtil.prettyPrintType(f.getTypeNode()));
}
@Test
void testLambdaWithoutType() throws Exception {
ASTCompilationUnit acu = java8.parse(TEST_LAMBDA_WITHOUT_TYPE);
ASTLambdaExpression lambda = acu.getFirstDescendantOfType(ASTLambdaExpression.class);
ASTVariableDeclaratorId f = lambda.getFirstDescendantOfType(ASTVariableDeclaratorId.class);
assertNull(f.getTypeNode());
}
private static final String TYPE_NAME_NODE = "public class Test {\n private String bar;\n}";
private static final String EXCEPTION_PARAMETER = "public class Test { { try {} catch(Exception ie) {} } }";
private static final String TEST_ANNOTATIONS = "public class Foo {\n public void bar(@A1 @A2 String s) {}\n}";
private static final String TEST_LAMBDA_WITH_TYPE =
"public class Foo {\n public void bar() {\n FileFilter java = (File f) -> f.getName().endsWith(\".java\");\n }\n}\n";
private static final String TEST_LAMBDA_WITHOUT_TYPE =
"public class Foo {\n public void bar() {\n FileFilter java2 = f -> f.getName().endsWith(\".java\");\n }\n}\n";
}
| 3,014 | 42.695652 | 138 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java9TreeDumpTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java9TreeDumpTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java9 = JavaParsingHelper.DEFAULT
.withDefaultVersion("9")
.withResourceContext(Java9TreeDumpTest.class, "jdkversiontests/java9");
@Test
void testModule() {
doTest("jdk9_module_info");
}
@Test
void testAnnotatedModule() {
doTest("jdk9_module_info_with_annot");
}
@Override
public @NonNull BaseParsingHelper<?, ?> getParser() {
return java9;
}
}
| 920 | 25.314286 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchStatementTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTSwitchStatementTest extends BaseParserTest {
@Test
void exhaustiveEnumSwitchWithDefault() {
ASTSwitchStatement switchStatement = java.parse(
"import java.nio.file.AccessMode; class Foo { void bar(AccessMode m) {"
+ "switch (m) { case READ: break; default: break; } } }")
.descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStatement.isExhaustiveEnumSwitch()); // this should not throw a NPE...
assertTrue(switchStatement.hasDefaultCase());
assertTrue(switchStatement.isFallthroughSwitch());
}
@Test
void defaultCaseWithArrowBlock() {
ASTSwitchStatement switchStatement =
java.parse("class Foo { void bar(int x) {switch (x) { default -> { } } } }")
.descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStatement.isExhaustiveEnumSwitch());
assertTrue(switchStatement.iterator().hasNext());
assertTrue(switchStatement.hasDefaultCase());
assertFalse(switchStatement.isFallthroughSwitch());
}
@Test
void emptySwitch() {
ASTSwitchStatement switchStatement =
java.parse("class Foo { void bar(int x) {switch (x) { } } }")
.descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStatement.isExhaustiveEnumSwitch());
assertFalse(switchStatement.iterator().hasNext());
assertFalse(switchStatement.hasDefaultCase());
assertFalse(switchStatement.isFallthroughSwitch());
}
@Test
void defaultCaseWithArrowExprs() {
ASTSwitchStatement switchStatement =
java.parse(
"import net.sourceforge.pmd.lang.java.rule.bestpractices.switchstmtsshouldhavedefault.SimpleEnum;\n"
+ "\n"
+ " public class Foo {\n"
+ " void bar(SimpleEnum x) {\n"
+ " switch (x) {\n"
+ " case FOO -> System.out.println(\"it is on\");\n"
+ " case BAR -> System.out.println(\"it is off\");\n"
+ " default -> System.out.println(\"it is neither on nor off - should not happen? maybe null?\");\n"
+ " }\n"
+ " }\n"
+ " }")
.descendants(ASTSwitchStatement.class).firstOrThrow();
assertFalse(switchStatement.isExhaustiveEnumSwitch());
assertTrue(switchStatement.iterator().hasNext());
assertFalse(switchStatement.isFallthroughSwitch());
assertTrue(switchStatement.hasDefaultCase());
}
}
| 3,183 | 43.84507 | 143 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java10Test.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.types.JClassType;
import net.sourceforge.pmd.lang.java.types.TypeSystem;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
class Java10Test {
private final JavaParsingHelper java10 =
JavaParsingHelper.DEFAULT.withDefaultVersion("10")
.withResourceContext(Java10Test.class, "jdkversiontests/java10/");
private final JavaParsingHelper java9 = java10.withDefaultVersion("9");
@Test
void testLocalVarInferenceBeforeJava10() {
// note, it can be parsed, but we'll have a ReferenceType of "var"
List<ASTLocalVariableDeclaration> localVars = java9.parseResource("LocalVariableTypeInference.java")
.findDescendantsOfType(ASTLocalVariableDeclaration.class);
assertEquals(3, localVars.size());
ASTVariableDeclaratorId varId = localVars.get(0).getVarIds().firstOrThrow();
// first: var list = new ArrayList<String>();
assertTrue(varId.getTypeNode() instanceof ASTClassOrInterfaceType);
// in that case, we don't have a class named "var", so the type will be null
assertTrue(varId.getTypeMirror().getSymbol().isUnresolved());
// check the type of the variable initializer's expression
ASTExpression initExpression = varId.getInitializer();
assertTrue(TypeTestUtil.isA(ArrayList.class, initExpression), "type should be ArrayList");
}
@Test
void testLocalVarInferenceCanBeParsedJava10() {
ASTCompilationUnit compilationUnit = java10.parseResource("LocalVariableTypeInference.java");
List<ASTLocalVariableDeclaration> localVars = compilationUnit.findDescendantsOfType(ASTLocalVariableDeclaration.class);
assertEquals(3, localVars.size());
TypeSystem ts = compilationUnit.getTypeSystem();
JClassType stringT = (JClassType) ts.typeOf(ts.getClassSymbol(String.class), false);
// first: var list = new ArrayList<String>();
assertNull(localVars.get(0).getTypeNode());
ASTVariableDeclaratorId varDecl = localVars.get(0).getVarIds().firstOrThrow();
assertEquals(ts.parameterise(ts.getClassSymbol(ArrayList.class), listOf(stringT)), varDecl.getTypeMirror(), "type should be ArrayList<String>");
// second: var stream = list.stream();
assertNull(localVars.get(1).getTypeNode());
ASTVariableDeclaratorId varDecl2 = localVars.get(1).getVarIds().firstOrThrow();
assertEquals(ts.parameterise(ts.getClassSymbol(Stream.class), listOf(stringT)),
varDecl2.getTypeMirror(),
"type should be Stream<String>");
// third: var s = "Java 10";
assertNull(localVars.get(2).getTypeNode());
ASTVariableDeclaratorId varDecl3 = localVars.get(2).getVarIds().firstOrThrow();
assertEquals(stringT, varDecl3.getTypeMirror(), "type should be String");
}
@Test
void testForLoopWithVar() {
List<ASTLocalVariableDeclaration> localVars = java10.parseResource("LocalVariableTypeInferenceForLoop.java")
.findDescendantsOfType(ASTLocalVariableDeclaration.class);
assertEquals(1, localVars.size());
assertNull(localVars.get(0).getTypeNode());
ASTVariableDeclaratorId varDecl = localVars.get(0).getVarIds().firstOrThrow();
assertSame(varDecl.getTypeSystem().INT, varDecl.getTypeMirror(), "type should be int");
}
@Test
void testForLoopEnhancedWithVar() {
List<ASTLocalVariableDeclaration> localVars = java10.parseResource("LocalVariableTypeInferenceForLoopEnhanced.java")
.findDescendantsOfType(ASTLocalVariableDeclaration.class);
assertEquals(1, localVars.size());
assertNull(localVars.get(0).getTypeNode());
ASTVariableDeclaratorId varDecl = localVars.get(0).getVarIds().firstOrThrow();
assertTrue(TypeTestUtil.isA(String.class, varDecl), "type should be String");
}
@Test
void testForLoopEnhancedWithVar2() {
List<ASTLocalVariableDeclaration> localVars = java10.parseResource("LocalVariableTypeInferenceForLoopEnhanced2.java")
.findDescendantsOfType(ASTLocalVariableDeclaration.class);
assertEquals(4, localVars.size());
assertNull(localVars.get(1).getTypeNode());
@NonNull ASTVariableDeclaratorId varDecl2 = localVars.get(1).getVarIds().firstOrThrow();
assertTrue(TypeTestUtil.isA(String.class, varDecl2), "type should be String");
assertNull(localVars.get(3).getTypeNode());
ASTVariableDeclaratorId varDecl4 = localVars.get(3).getVarIds().firstOrThrow();
assertSame(varDecl2.getTypeSystem().INT, varDecl4.getTypeMirror(), "type should be int");
}
@Test
void testTryWithResourcesWithVar() {
List<ASTResource> resources = java10.parseResource("LocalVariableTypeInferenceTryWithResources.java")
.findDescendantsOfType(ASTResource.class);
assertEquals(1, resources.size());
assertNull(resources.get(0).asLocalVariableDeclaration().getTypeNode());
ASTVariableDeclaratorId varId = resources.get(0).asLocalVariableDeclaration().getVarIds().firstOrThrow();
assertTrue(TypeTestUtil.isA(FileInputStream.class, varId), "type should be FileInputStream");
}
@Test
void testTypeResNullPointer() {
java10.parseResource("LocalVariableTypeInference_typeres.java");
}
}
| 6,331 | 45.903704 | 152 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.concurrent.TimeUnit;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.types.AstTestUtil;
class ParserCornersTest extends BaseJavaTreeDumpTest {
private final JavaParsingHelper java = JavaParsingHelper.DEFAULT.withResourceContext(getClass());
private final JavaParsingHelper java4 = java.withDefaultVersion("1.4");
private final JavaParsingHelper java5 = java.withDefaultVersion("1.5");
private final JavaParsingHelper java7 = java.withDefaultVersion("1.7");
private final JavaParsingHelper java8 = java.withDefaultVersion("1.8");
private final JavaParsingHelper java9 = java.withDefaultVersion("9");
private final JavaParsingHelper java15 = java.withDefaultVersion("15");
@Override
public @NonNull BaseParsingHelper<?, ?> getParser() {
return java4;
}
@Test
void testInvalidUnicodeEscape() {
MalformedSourceException thrown = assertThrows(MalformedSourceException.class, // previously Error
() -> java.parse("\\u00k0", null, FileId.fromPathLikeString("x/filename.java")));
assertThat(thrown.getMessage(), startsWith("Source format error in file 'x/filename.java' at line 1, column 1: Invalid unicode escape"));
}
/**
* #1107 PMD 5.0.4 couldn't parse call of parent outer java class method
* from inner class.
*/
@Test
void testInnerOuterClass() {
java7.parse("/**\n" + " * @author azagorulko\n" + " *\n" + " */\n"
+ "public class TestInnerClassCallsOuterParent {\n" + "\n" + " public void test() {\n"
+ " new Runnable() {\n" + " @Override\n" + " public void run() {\n"
+ " TestInnerClassCallsOuterParent.super.toString();\n" + " }\n"
+ " };\n" + " }\n" + "}\n");
}
/**
* #888 PMD 6.0.0 can't parse valid <> under 1.8.
*/
@Test
void testDiamondUsageJava8() {
java8.parse("public class PMDExceptionTest {\n"
+ " private Component makeUI() {\n"
+ " String[] model = {\"123456\", \"7890\"};\n"
+ " JComboBox<String> comboBox = new JComboBox<>(model);\n"
+ " comboBox.setEditable(true);\n"
+ " comboBox.setEditor(new BasicComboBoxEditor() {\n"
+ " private Component editorComponent;\n"
+ " @Override public Component getEditorComponent() {\n"
+ " if (editorComponent == null) {\n"
+ " JTextField tc = (JTextField) super.getEditorComponent();\n"
+ " editorComponent = new JLayer<>(tc, new ValidationLayerUI<>());\n"
+ " }\n"
+ " return editorComponent;\n"
+ " }\n"
+ " });\n"
+ " JPanel p = new JPanel();\n"
+ " p.add(comboBox);\n"
+ " return p;\n"
+ " }\n"
+ "}");
}
@Test
void testUnicodeEscapes() {
// todo i'd like to test the coordinates of the literals, but this has to wait for java-grammar to be merged
java8.parse("public class Foo { String[] s = { \"Ven\\u00E4j\\u00E4\" }; }");
}
@Test
void testUnicodeEscapes2() {
java.parse("\n"
+ "public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle {\n"
+ "\n"
+ " String ACT[] = new String[] {\"Acre \\u6642\\u9593\", \"ACT\",\n"
+ " \"Acre \\u590f\\u4ee4\\u6642\\u9593\", \"ACST\",\n"
+ " \"Acre \\u6642\\u9593\", \"ACT\"};"
+ "}");
}
@Test
void testUnicodeEscapesInComment() {
java.parse("class Foo {"
+ "\n"
+ " /**\n"
+ " * The constant value of this field is the smallest value of type\n"
+ " * {@code char}, {@code '\\u005Cu0000'}.\n"
+ " *\n"
+ " * @since 1.0.2\n"
+ " */\n"
+ " public static final char MIN_VALUE = '\\u0000';\n"
+ "\n"
+ " /**\n"
+ " * The constant value of this field is the largest value of type\n"
+ " * {@code char}, {@code '\\u005C\\uFFFF'}.\n"
+ " *\n"
+ " * @since 1.0.2\n"
+ " */\n"
+ " public static final char MAX_VALUE = '\\uFFFF';"
+ "}");
}
@Test
final void testGetFirstASTNameImageNull() {
java4.parse("public class Test {\n"
+ " void bar() {\n"
+ " abstract class X { public abstract void f(); }\n"
+ " class Y extends X { public void f() { new Y().f(); } }\n"
+ " }\n"
+ "}");
}
@Test
void testCastLookaheadProblem() {
java4.parse("public class BadClass {\n public Class foo() {\n return (byte[].class);\n }\n}");
}
@Test
void testTryWithResourcesConcise() {
// https://github.com/pmd/pmd/issues/3697
java9.parse("import java.io.InputStream;\n"
+ "public class Foo {\n"
+ " public InputStream in;\n"
+ " public void bar() {\n"
+ " Foo f = this;\n"
+ " try (f.in) {\n"
+ " }\n"
+ " }\n"
+ "}");
}
@Test
void testTryWithResourcesThis() {
// https://github.com/pmd/pmd/issues/3697
java9.parse("import java.io.InputStream;\n"
+ "public class Foo {\n"
+ " public InputStream in;\n"
+ " public void bar() {\n"
+ " try (this.in) {\n"
+ " }\n"
+ " }\n"
+ "}");
}
@Test
void testTextBlockWithQuotes() {
// https://github.com/pmd/pmd/issues/4364
java15.parse("public class Foo {\n"
+ " private String content = \"\"\"\n"
+ " <div class=\"invalid-class></div>\n"
+ " \"\"\";\n"
+ "}");
}
/**
* Tests a specific generic notation for calling methods. See:
* https://jira.codehaus.org/browse/MPMD-139
*/
@Test
void testGenericsProblem() {
String code = "public class Test {\n"
+ " public void test() {\n"
+ " String o = super.<String> doStuff(\"\");\n"
+ " }\n"
+ "}";
java5.parse(code);
java7.parse(code);
}
@Test
void testUnicodeIndent() {
// https://github.com/pmd/pmd/issues/3423
java7.parseResource("UnicodeIdentifier.java");
}
@Test
void testParsersCases15() {
doTest("ParserCornerCases", java5);
}
@Test
void testParsersCases17() {
doTest("ParserCornerCases17", java7);
}
@Test
void testParsersCases18() {
doTest("ParserCornerCases18", java8);
}
/**
* Test for https://sourceforge.net/p/pmd/bugs/1333/
*/
@Test
void testLambdaBug1333() {
doTest("LambdaBug1333", java8);
}
@Test
void testLambdaBug1470() {
doTest("LambdaBug1470", java8);
}
/**
* Test for https://sourceforge.net/p/pmd/bugs/1355/
*/
@Test
void emptyFileJustComment() {
getParser().parse("// just a comment");
}
@Test
void testBug1429ParseError() {
doTest("Bug1429", java8);
}
@Test
void testBug1530ParseError() {
doTest("Bug1530", java8);
}
@Test
void testGitHubBug207() {
doTest("GitHubBug207", java8);
}
@Test
void testLambda2783() {
java8.parseResource("LambdaBug2783.java");
}
@Test
void testGitHubBug2767() {
// PMD fails to parse an initializer block.
// PMD 6.26.0 parses this code just fine.
java.withDefaultVersion("16")
.parse("class Foo {\n"
+ " {final int I;}\n"
+ "}\n");
}
@Test
void testBug206() {
doTest("LambdaBug206", java8);
}
@Test
void testGitHubBug208ParseError() {
doTest("GitHubBug208", java5);
}
@Test
void testGitHubBug309() {
doTest("GitHubBug309", java8);
}
@Test
@Timeout(value = 30, unit = TimeUnit.SECONDS)
void testInfiniteLoopInLookahead() {
assertThrows(ParseException.class, () ->
// https://github.com/pmd/pmd/issues/3117
java8.parseResource("InfiniteLoopInLookahead.java"));
}
@Test
void stringConcatentationShouldNotBeCast() {
// https://github.com/pmd/pmd/issues/1484
String code = "public class Test {\n" + " public static void main(String[] args) {\n"
+ " System.out.println(\"X\" + (args) + \"Y\");\n" + " }\n" + "}";
assertEquals(0, java8.parse(code).descendants(ASTCastExpression.class).count());
}
/**
* Empty statements should be allowed.
*
* @see <a href="https://github.com/pmd/pmd/issues/378">github issue 378</a>
*/
@Test
void testEmptyStatements1() {
doTest("EmptyStmts1");
}
@Test
void testEmptyStatements2() {
doTest("EmptyStmts2");
}
@Test
void testEmptyStatements3() {
doTest("EmptyStmts3");
}
@Test
void testMethodReferenceConfused() {
ASTCompilationUnit ast = java.parseResource("MethodReferenceConfused.java", "10");
ASTVariableDeclaratorId varWithMethodName = AstTestUtil.varId(ast, "method");
ASTVariableDeclaratorId someObject = AstTestUtil.varId(ast, "someObject");
assertThat(varWithMethodName.getLocalUsages(), empty());
assertThat(someObject.getLocalUsages(), hasSize(1));
ASTNamedReferenceExpr usage = someObject.getLocalUsages().get(0);
assertThat(usage.getParent(), instanceOf(ASTCastExpression.class));
}
@Test
void testSwitchWithFallthrough() {
doTest("SwitchWithFallthrough");
}
@Test
void testSwitchStatements() {
doTest("SwitchStatements");
}
@Test
void testSynchronizedStatements() {
doTest("SynchronizedStmts");
}
@Test
void testGithubBug3101UnresolvedTypeParams() {
java.parseResource("GitHubBug3101.java");
}
@Test
void testGitHubBug3642() {
doTest("GitHubBug3642");
}
}
| 12,291 | 33.049861 | 145 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaQualifiedNameTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
/**
* @author Clément Fournier
*/
class JavaQualifiedNameTest {
private <T extends Node> List<T> getNodes(Class<T> target, String code) {
return JavaParsingHelper.DEFAULT.withDefaultVersion("15").getNodes(target, code);
}
@Test
void testEmptyPackage() {
final String TEST = "class Foo {}";
List<ASTClassOrInterfaceDeclaration> nodes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
for (ASTClassOrInterfaceDeclaration coid : nodes) {
assertEquals("Foo", coid.getBinaryName());
assertEquals("", coid.getPackageName());
}
}
@Test
void testPackage() {
final String TEST = "package foo.bar; class Bzaz{}";
List<ASTClassOrInterfaceDeclaration> nodes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
for (ASTClassOrInterfaceDeclaration coid : nodes) {
assertEquals("foo.bar.Bzaz", coid.getBinaryName());
}
}
@Test
void testNestedClass() {
final String TEST = "package foo.bar; class Bzaz{ class Bor{ class Foo{}}}";
List<ASTClassOrInterfaceDeclaration> nodes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
for (ASTClassOrInterfaceDeclaration coid : nodes) {
if ("Foo".equals(coid.getImage())) {
assertEquals("foo.bar.Bzaz$Bor$Foo", coid.getBinaryName());
}
}
}
@Test
void testNestedEnum() {
final String TEST = "package foo.bar; class Foo { enum Bzaz{HOO;}}";
List<ASTEnumDeclaration> nodes = getNodes(ASTEnumDeclaration.class, TEST);
for (ASTEnumDeclaration coid : nodes) {
assertEquals("foo.bar.Foo$Bzaz", coid.getBinaryName());
assertEquals("Bzaz", coid.getSimpleName());
assertEquals("foo.bar", coid.getPackageName());
}
}
@Test
void testEnum() {
final String TEST = "package foo.bar; enum Bzaz{HOO;}";
List<ASTEnumDeclaration> nodes = getNodes(ASTEnumDeclaration.class, TEST);
for (ASTEnumDeclaration coid : nodes) {
assertEquals("foo.bar.Bzaz", coid.getBinaryName());
assertEquals("Bzaz", coid.getSimpleName());
assertEquals("foo.bar", coid.getPackageName());
}
}
@Test
void testNestedEmptyPackage() {
final String TEST = "class Bzaz{ class Bor{ class Foo{}}}";
List<ASTClassOrInterfaceDeclaration> nodes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
for (ASTClassOrInterfaceDeclaration coid : nodes) {
if ("Foo".equals(coid.getSimpleName())) {
assertEquals("Bzaz$Bor$Foo", coid.getBinaryName());
assertEquals("", coid.getPackageName());
}
}
}
@Test
void testSimpleLocalClass() {
final String TEST = "package bar; class Boron { public void foo(String j) { class Local {} } }";
List<ASTClassOrInterfaceDeclaration> classes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
assertEquals("bar.Boron$1Local", classes.get(1).getBinaryName());
}
@Test
void testLocalClassNameClash() {
final String TEST = "package bar; class Bzaz{ void foo() { class Local {} } {// initializer\n class Local {}}}";
List<ASTClassOrInterfaceDeclaration> classes
= getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
assertEquals("bar.Bzaz$1Local", classes.get(1).getBinaryName());
assertEquals("bar.Bzaz$2Local", classes.get(2).getBinaryName());
}
@Test
void testLocalClassDeepNesting() {
final String TEST
= "class Bzaz{ void foo() { "
+ " class Local { "
+ " class Nested {"
+ " {"
+ " class InnerLocal{}"
+ " }"
+ " }"
+ " }"
+ "}}";
List<ASTClassOrInterfaceDeclaration> classes
= getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
assertEquals("Bzaz$1Local", classes.get(1).getBinaryName());
assertEquals("Local", classes.get(1).getSimpleName());
assertTrue(classes.get(1).isLocal());
assertFalse(classes.get(1).isNested());
assertEquals("Bzaz$1Local$Nested", classes.get(2).getBinaryName());
assertFalse(classes.get(2).isLocal());
assertTrue(classes.get(2).isNested());
assertEquals("Bzaz$1Local$Nested$1InnerLocal", classes.get(3).getBinaryName());
assertTrue(classes.get(3).isLocal());
assertFalse(classes.get(3).isNested());
}
@Test
void testAnonymousClass() {
final String TEST
= "class Bzaz{ void foo() { "
+ " new Runnable() {"
+ " public void run() {}"
+ " };"
+ "}}";
List<ASTAnonymousClassDeclaration> classes = getNodes(ASTAnonymousClassDeclaration.class, TEST);
assertEquals(("Bzaz$1"), classes.get(0).getBinaryName());
assertFalse(classes.get(0).isLocal());
assertTrue(classes.get(0).isAnonymous());
assertEquals("", classes.get(0).getSimpleName());
}
@Test
void testMultipleAnonymousClasses() {
final String TEST
= "class Bzaz{ void foo() { "
+ " new Runnable() {"
+ " public void run() {}"
+ " };"
+ " new Runnable() {"
+ " public void run() {}"
+ " };"
+ "}}";
List<ASTAnonymousClassDeclaration> classes = getNodes(ASTAnonymousClassDeclaration.class, TEST);
assertNotEquals(classes.get(0), classes.get(1));
assertEquals("Bzaz$1", classes.get(0).getBinaryName());
assertEquals("Bzaz$2", classes.get(1).getBinaryName());
}
@Test
void testNestedAnonymousClass() {
final String TEST
= "class Bzaz{ void foo() {"
+ " new Runnable() {"
+ " public void run() {"
+ " new Runnable() {"
+ " public void run() {}"
+ " };"
+ " }"
+ " };"
+ "}}";
List<ASTAnonymousClassDeclaration> classes = getNodes(ASTAnonymousClassDeclaration.class, TEST);
assertNotEquals(classes.get(0), classes.get(1));
assertEquals("Bzaz$1", classes.get(0).getBinaryName());
assertEquals("Bzaz$1$1", classes.get(1).getBinaryName());
}
@Test
void testLocalInAnonymousClass() {
final String TEST
= "class Bzaz{ void foo() {"
+ " new Runnable() {"
+ " public void run() {"
+ " class FooRunnable {}"
+ " }"
+ " };"
+ "}}";
List<ASTClassOrInterfaceDeclaration> classes = getNodes(ASTClassOrInterfaceDeclaration.class, TEST);
assertTrue(classes.get(1).isLocal());
assertEquals("Bzaz$1$1FooRunnable", classes.get(1).getBinaryName());
}
}
| 7,595 | 30.915966 | 120 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java8Test.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java8Test {
private final JavaParsingHelper java8 =
JavaParsingHelper.DEFAULT.withDefaultVersion("8")
.withResourceContext(Java8Test.class);
@Test
void interfaceMethodShouldBeParseable() {
java8.parse("interface WithStaticAndDefaultMethod {\n"
+ " static void performOn() {\n"
+ " }\n"
+ "\n"
+ " default void myToString() {\n"
+ " }\n"
+ " }\n");
}
@Test
void repeatableAnnotationsMethodShouldBeParseable() {
java8.parse("@Multitude(\"1\")\n"
+ "@Multitude(\"2\")\n"
+ "@Multitude(\"3\")\n"
+ "@Multitude(\"4\")\n"
+ "public class UsesRepeatableAnnotations {\n"
+ "\n"
+ " @Repeatable(Multitudes.class)\n"
+ " @Retention(RetentionPolicy.RUNTIME)\n"
+ " @interface Multitude {\n"
+ " String value();\n"
+ " }\n"
+ "\n"
+ " @Retention(RetentionPolicy.RUNTIME)\n"
+ " @interface Multitudes {\n"
+ " Multitude[] value();\n"
+ " }\n"
+ "\n"
+ "}");
}
}
| 1,794 | 35.632653 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTBooleanLiteralTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTBooleanLiteralTest extends BaseParserTest {
@Test
void testTrue() {
List<ASTBooleanLiteral> ops = java.getNodes(ASTBooleanLiteral.class, TEST1);
ASTBooleanLiteral b = ops.get(0);
assertTrue(b.isTrue());
}
@Test
void testFalse() {
List<ASTBooleanLiteral> ops = java.getNodes(ASTBooleanLiteral.class, TEST2);
ASTBooleanLiteral b = ops.get(0);
assertFalse(b.isTrue());
}
private static final String TEST1 = "class Foo { \n boolean bar = true; \n} ";
private static final String TEST2 = "class Foo { \n boolean bar = false; \n} ";
}
| 989 | 26.5 | 84 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTPackageDeclarationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTPackageDeclarationTest extends BaseParserTest {
private static final String PACKAGE_INFO_ANNOTATED = "@Deprecated\npackage net.sourceforge.pmd.foobar;\n";
/**
* Regression test for bug 3524607.
*/
@Test
void testPackageName() {
ASTCompilationUnit nodes = java.parse(PACKAGE_INFO_ANNOTATED);
assertEquals("net.sourceforge.pmd.foobar", nodes.getPackageDeclaration().getName());
assertEquals("net.sourceforge.pmd.foobar", nodes.getPackageName());
}
}
| 799 | 27.571429 | 110 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/Java19PreviewTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
class Java19PreviewTreeDumpTest extends BaseTreeDumpTest {
private final JavaParsingHelper java19p =
JavaParsingHelper.DEFAULT.withDefaultVersion("19-preview")
.withResourceContext(Java19PreviewTreeDumpTest.class, "jdkversiontests/java19p/");
private final JavaParsingHelper java19 = java19p.withDefaultVersion("19");
Java19PreviewTreeDumpTest() {
super(new RelevantAttributePrinter(), ".java");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return java19p;
}
@Test
void dealingWithNullBeforeJava19Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java19.parseResource("DealingWithNull.java"));
assertTrue(thrown.getMessage().contains("Null in switch cases is a preview feature of JDK 19, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void dealingWithNull() {
doTest("DealingWithNull");
}
@Test
void enhancedTypeCheckingSwitch() {
doTest("EnhancedTypeCheckingSwitch");
}
@Test
void exhaustiveSwitch() {
doTest("ExhaustiveSwitch");
}
@Test
void guardedAndParenthesizedPatternsBeforeJava19Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java19.parseResource("GuardedAndParenthesizedPatterns.java"));
assertTrue(thrown.getMessage().contains("Patterns in switch statements is a preview feature of JDK 19, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void guardedAndParenthesizedPatterns() {
doTest("GuardedAndParenthesizedPatterns");
}
@Test
void patternsInSwitchLabelsBeforeJava19Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java19.parseResource("PatternsInSwitchLabels.java"));
assertTrue(thrown.getMessage().contains("Patterns in switch statements is a preview feature of JDK 19, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
@Test
void patternsInSwitchLabels() {
doTest("PatternsInSwitchLabels");
}
@Test
void refiningPatternsInSwitch() {
doTest("RefiningPatternsInSwitch");
}
@Test
void scopeOfPatternVariableDeclarations() {
doTest("ScopeOfPatternVariableDeclarations");
}
@Test
void recordPatterns() {
doTest("RecordPatterns");
}
@Test
void recordPatternsBeforeJava19Preview() {
ParseException thrown = assertThrows(ParseException.class, () -> java19.parseResource("RecordPatterns.java"));
assertTrue(thrown.getMessage().contains("Deconstruction patterns is a preview feature of JDK 19, you should select your language version accordingly"),
"Unexpected message: " + thrown.getMessage());
}
}
| 3,592 | 34.574257 | 165 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ASTImportDeclarationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.java.BaseParserTest;
class ASTImportDeclarationTest extends BaseParserTest {
@Test
void testImportOnDemand() {
List<ASTImportDeclaration> ops = java.getNodes(ASTImportDeclaration.class, TEST1);
assertTrue(ops.get(0).isImportOnDemand());
}
@Test
void testGetImportedNameNode() {
ASTImportDeclaration i = java.getNodes(ASTImportDeclaration.class, TEST2).get(0);
assertEquals("foo.bar.Baz", i.getImportedName());
}
@Test
void testStaticImport() {
List<ASTImportDeclaration> ops = java.getNodes(ASTImportDeclaration.class, TEST3);
ASTImportDeclaration i = ops.get(0);
assertTrue(i.isStatic());
}
@Test
void testStaticImportFailsWithJDK14() {
assertThrows(ParseException.class, () -> java.parse(TEST3, "1.4"));
}
private static final String TEST1 = "import foo.bar.*;\npublic class Foo {}";
private static final String TEST2 = "import foo.bar.Baz;\npublic class Foo {}";
private static final String TEST3 = "import static foo.bar.Baz;\npublic class Foo {}";
}
| 1,546 | 29.94 | 90 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/testdata/InterfaceWithNestedClass.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast.testdata;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public interface InterfaceWithNestedClass {
Map<String, String> MAPPING = Collections.unmodifiableMap(new HashMap<String, String>() {
private static final long serialVersionUID = 3855526803226948630L;
{
put("X", "10");
put("L", "50");
put("C", "100");
put("M", "1000");
}
});
}
| 579 | 25.363636 | 93 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/internal/JavaAstUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast.internal;
import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.flattenOperands;
import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isStringConcatExpr;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression;
import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess;
class JavaAstUtilTest extends BaseParserTest {
@Test
void testFlattenConcatOperands() {
ASTExpression e = parseExpr("s1+s2+s3");
assertTrue(isStringConcatExpr(e));
assertEquals(e.descendants(ASTVariableAccess.class).toList(),
flattenOperands(e).toList());
}
@Test
void testFlattenConcatOperandsRespectsTyping() {
ASTInfixExpression e = (ASTInfixExpression) parseExpr("i+j+s2+s3");
assertTrue(isStringConcatExpr(e));
ASTInfixExpression left = (ASTInfixExpression) e.getLeftOperand();
assertTrue(isStringConcatExpr(left));
// This is (i+j)
// vvvvvvvvvvvvvvvvvvvvv
assertEquals(listOf(left.getLeftOperand(), left.getRightOperand(), e.getRightOperand()),
flattenOperands(e).toList());
}
}
| 1,643 | 35.533333 | 96 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/internal/PrettyPrintingUtilTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast.internal;
import static net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil.displaySignature;
import static net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil.prettyPrint;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.util.StringUtil;
class PrettyPrintingUtilTest extends BaseParserTest {
@Test
void displaySignatureTestWithExtraDimensions() {
ASTCompilationUnit root = java.parse("class A { public void foo(String[] a[]) {} }");
ASTMethodDeclaration m = root.descendants(ASTMethodDeclaration.class).firstOrThrow();
assertEquals("foo(String[][])", displaySignature(m));
}
@Test
void ppMethodCall() {
ASTCompilationUnit root = java.parse("class A { { foo(1); this.foo(1); A.this.foo(); } }");
List<ASTMethodCall> m = root.descendants(ASTMethodCall.class).toList();
assertThat(prettyPrint(m.get(0)), contentEquals("foo(1)"));
assertThat(prettyPrint(m.get(1)), contentEquals("this.foo(1)"));
assertThat(prettyPrint(m.get(2)), contentEquals("A.this.foo()"));
}
@Test
void ppMethodCallArgsTooBig() {
ASTCompilationUnit root = java.parse("class A { { this.foo(\"a long string\", 12, 12, 12, 12, 12); } }");
@NonNull ASTMethodCall m = root.descendants(ASTMethodCall.class).firstOrThrow();
assertThat(prettyPrint(m), contentEquals("this.foo(\"a long string\", 12...)"));
}
@Test
void ppMethodCallOnCast() {
ASTCompilationUnit root = java.parse("class A { { ((Object) this).foo(12); } }");
@NonNull ASTMethodCall m = root.descendants(ASTMethodCall.class).firstOrThrow();
assertThat(prettyPrint(m), contentEquals("((Object) this).foo(12)"));
}
private static Matcher<CharSequence> contentEquals(String str) {
return new BaseMatcher<CharSequence>() {
@Override
public boolean matches(Object o) {
return o instanceof CharSequence && str.contentEquals((CharSequence) o);
}
@Override
public void describeTo(Description description) {
description.appendText("a char sequence with content \"" + StringUtil.escapeJava(str) + "\"");
}
};
}
}
| 2,918 | 37.407895 | 113 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/JavaMetricsProviderTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.Map;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider;
import net.sourceforge.pmd.lang.metrics.Metric;
/**
* @author Clément Fournier
*/
class JavaMetricsProviderTest {
private final JavaParsingHelper java8 = JavaParsingHelper.DEFAULT.withDefaultVersion("1.8");
@Test
void testComputeAllMetrics() {
ASTCompilationUnit acu = java8.parse("class Foo { void bar() { System.out.println(1); } }");
ASTAnyTypeDeclaration type = acu.getTypeDeclarations().firstOrThrow();
LanguageMetricsProvider provider = acu.getAstInfo().getLanguageProcessor().services().getLanguageMetricsProvider();
Map<Metric<?, ?>, Number> results = provider.computeAllMetricsFor(type);
assertEquals(9, results.size());
}
@Test
void testThereIsNoMemoisation() {
ASTAnyTypeDeclaration tdecl1 = java8.parse("class Foo { void bar() { System.out.println(1); } }")
.getTypeDeclarations().firstOrThrow();
LanguageMetricsProvider provider = tdecl1.getAstInfo().getLanguageProcessor().services().getLanguageMetricsProvider();
Map<Metric<?, ?>, Number> reference = provider.computeAllMetricsFor(tdecl1);
// same name, different characteristics
ASTAnyTypeDeclaration tdecl2 = java8.parse("class Foo { void bar(){} \npublic void hey() { System.out.println(1); } }")
.getTypeDeclarations().firstOrThrow();
Map<Metric<?, ?>, Number> secondTest = provider.computeAllMetricsFor(tdecl2);
assertNotEquals(reference, secondTest);
}
}
| 2,127 | 32.25 | 127 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/MetricsMemoizationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.BaseParserTest;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase;
import net.sourceforge.pmd.lang.java.metrics.testdata.MetricsVisitorTestData;
import net.sourceforge.pmd.lang.metrics.Metric;
import net.sourceforge.pmd.lang.metrics.MetricOptions;
import net.sourceforge.pmd.lang.metrics.MetricsUtil;
/**
* @author Clément Fournier
*/
class MetricsMemoizationTest extends BaseParserTest {
private final Metric<Node, Integer> randomMetric = randomMetric();
private static Metric<Node, Integer> randomMetric() {
Random capturedRandom = new Random();
return Metric.of((t, opts) -> capturedRandom.nextInt(), t -> t, "randomMetric");
}
@Test
void memoizationTest() {
ASTCompilationUnit acu = java.parseClass(MetricsVisitorTestData.class);
List<Integer> expected = visitWith(acu, true);
List<Integer> real = visitWith(acu, false);
assertEquals(expected, real);
}
@Test
void forceMemoizationTest() {
ASTCompilationUnit acu = java.parseClass(MetricsVisitorTestData.class);
List<Integer> reference = visitWith(acu, true);
List<Integer> real = visitWith(acu, true);
assertEquals(reference.size(), real.size());
// we force recomputation so each result should be different
for (int i = 0; i < reference.size(); i++) {
assertNotEquals(reference.get(i), real.get(i));
}
}
private List<Integer> visitWith(ASTCompilationUnit acu, final boolean force) {
final List<Integer> result = new ArrayList<>();
acu.acceptVisitor(new JavaVisitorBase<Object, Object>() {
@Override
public Object visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, Object data) {
Integer value = MetricsUtil.computeMetric(randomMetric, node, MetricOptions.emptyOptions(), force);
if (value != null) {
result.add(value);
}
return super.visitMethodOrCtor(node, data);
}
@Override
public Object visitTypeDecl(ASTAnyTypeDeclaration node, Object data) {
Integer value = MetricsUtil.computeMetric(randomMetric, node, MetricOptions.emptyOptions(), force);
if (value != null) {
result.add(value);
}
return super.visitTypeDecl(node, data);
}
}, null);
return result;
}
}
| 3,140 | 31.71875 | 115 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/NcssTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import java.util.Map;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.NcssOption;
import net.sourceforge.pmd.lang.metrics.MetricOption;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* @author Clément Fournier
*/
public class NcssTestRule extends JavaIntMetricTestRule {
static final PropertyDescriptor<Boolean> REPORT_CLASSES =
PropertyFactory.booleanProperty("reportClasses")
.desc("...")
.defaultValue(false).build();
public NcssTestRule() {
super(JavaMetrics.NCSS);
definePropertyDescriptor(REPORT_CLASSES);
}
@Override
protected boolean reportOn(Node node) {
return super.reportOn(node)
&& (node instanceof ASTMethodOrConstructorDeclaration
|| getProperty(REPORT_CLASSES) && node instanceof ASTAnyTypeDeclaration);
}
@Override
protected Map<String, MetricOption> optionMappings() {
Map<String, MetricOption> mappings = super.optionMappings();
mappings.put(NcssOption.COUNT_IMPORTS.valueName(), NcssOption.COUNT_IMPORTS);
return mappings;
}
}
| 1,578 | 32.595745 | 85 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/JavaDoubleMetricTestRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import java.util.Locale;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.metrics.Metric;
import net.sourceforge.pmd.test.AbstractMetricTestRule;
/**
*
*/
public abstract class JavaDoubleMetricTestRule extends AbstractMetricTestRule.OfDouble {
protected JavaDoubleMetricTestRule(Metric<?, Double> metric) {
super(metric);
}
@Override
protected boolean reportOn(Node node) {
return super.reportOn(node)
&& (node instanceof ASTMethodOrConstructorDeclaration
|| node instanceof ASTAnyTypeDeclaration);
}
@Override
protected String violationMessage(Node node, Double result) {
String fmt = String.format(Locale.ROOT, "%.4f", result);
return AllMetricsTest.formatJavaMessage(node, fmt, super.violationMessage(node, result));
}
}
| 1,125 | 29.432432 | 97 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/NoamTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
* @since 6.0.0
*/
public class NoamTestRule extends JavaIntMetricTestRule {
public NoamTestRule() {
super(JavaMetrics.NUMBER_OF_ACCESSORS);
}
}
| 396 | 19.894737 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/CycloTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import java.util.Map;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.CycloOption;
import net.sourceforge.pmd.lang.metrics.MetricOption;
/**
* Tests cyclo.
*
* @author Clément Fournier
*/
public class CycloTestRule extends JavaIntMetricTestRule {
public CycloTestRule() {
super(JavaMetrics.CYCLO);
}
@Override
protected Map<String, MetricOption> optionMappings() {
Map<String, MetricOption> mappings = super.optionMappings();
mappings.put(CycloOption.IGNORE_BOOLEAN_PATHS.valueName(), CycloOption.IGNORE_BOOLEAN_PATHS);
mappings.put(CycloOption.CONSIDER_ASSERT.valueName(), CycloOption.CONSIDER_ASSERT);
return mappings;
}
}
| 902 | 27.21875 | 101 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/LocTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
*/
public class LocTestRule extends JavaIntMetricTestRule {
public LocTestRule() {
super(JavaMetrics.LINES_OF_CODE);
}
}
| 372 | 19.722222 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/WocTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
* @since 6.0.0
*/
public class WocTestRule extends JavaDoubleMetricTestRule {
public WocTestRule() {
super(JavaMetrics.WEIGHT_OF_CLASS);
}
}
| 393 | 19.736842 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/AtfdTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
* @since 6.0.0
*/
public class AtfdTestRule extends JavaIntMetricTestRule {
public AtfdTestRule() {
super(JavaMetrics.ACCESS_TO_FOREIGN_DATA);
}
@Override
protected String violationMessage(Node node, Integer result) {
return super.violationMessage(node, result);
}
}
| 582 | 22.32 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/CfoTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import java.util.Map;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.ClassFanOutOption;
import net.sourceforge.pmd.lang.metrics.MetricOption;
/**
* @author Andreas Pabst
*/
public class CfoTestRule extends JavaIntMetricTestRule {
public CfoTestRule() {
super(JavaMetrics.FAN_OUT);
}
@Override
protected Map<String, MetricOption> optionMappings() {
Map<String, MetricOption> mappings = super.optionMappings();
mappings.put(ClassFanOutOption.INCLUDE_JAVA_LANG.valueName(), ClassFanOutOption.INCLUDE_JAVA_LANG);
return mappings;
}
}
| 798 | 26.551724 | 107 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/AllMetricsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil;
import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
/**
* Executes the metrics testing rules.
*
* @author Clément Fournier
*/
class AllMetricsTest extends SimpleAggregatorTst {
private static final String RULESET = "rulesets/java/metrics_test.xml";
@Override
public void setUp() {
addRule(RULESET, "CognitiveComplexityTest");
addRule(RULESET, "CycloTest");
addRule(RULESET, "NcssTest");
addRule(RULESET, "WmcTest");
addRule(RULESET, "LocTest");
addRule(RULESET, "NPathTest");
addRule(RULESET, "NopaTest");
addRule(RULESET, "NoamTest");
addRule(RULESET, "WocTest");
addRule(RULESET, "TccTest");
addRule(RULESET, "AtfdTest");
addRule(RULESET, "CfoTest");
}
static String formatJavaMessage(Node node, Object result, String defaultMessage) {
String qname = null;
if (node instanceof ASTAnyTypeDeclaration) {
qname = ((ASTAnyTypeDeclaration) node).getBinaryName();
} else if (node instanceof ASTMethodOrConstructorDeclaration) {
String enclosing = ((ASTMethodOrConstructorDeclaration) node).getEnclosingType().getBinaryName();
qname = enclosing + "#" + PrettyPrintingUtil.displaySignature((ASTMethodOrConstructorDeclaration) node);
}
if (qname != null) {
return "''" + qname + "'' has value " + result + ".";
}
return defaultMessage;
}
}
| 1,873 | 32.464286 | 116 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/NopaTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
* @since 6.0.0
*/
public class NopaTestRule extends JavaIntMetricTestRule {
public NopaTestRule() {
super(JavaMetrics.NUMBER_OF_PUBLIC_FIELDS);
}
}
| 400 | 20.105263 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/CognitiveComplexityTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Denis Borovikov
*/
public class CognitiveComplexityTestRule extends JavaIntMetricTestRule {
public CognitiveComplexityTestRule() {
super(JavaMetrics.COGNITIVE_COMPLEXITY);
}
}
| 410 | 21.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/WmcTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
*/
public class WmcTestRule extends JavaIntMetricTestRule {
public WmcTestRule() {
super(JavaMetrics.WEIGHED_METHOD_COUNT);
}
}
| 379 | 20.111111 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/JavaIntMetricTestRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration;
import net.sourceforge.pmd.lang.metrics.Metric;
import net.sourceforge.pmd.test.AbstractMetricTestRule;
/**
*
*/
public abstract class JavaIntMetricTestRule extends AbstractMetricTestRule.OfInt {
protected JavaIntMetricTestRule(Metric<?, Integer> metric) {
super(metric);
}
@Override
protected boolean reportOn(Node node) {
return super.reportOn(node)
&& (node instanceof ASTMethodOrConstructorDeclaration
|| node instanceof ASTAnyTypeDeclaration);
}
@Override
protected String violationMessage(Node node, Integer result) {
return AllMetricsTest.formatJavaMessage(node, result, super.violationMessage(node, result));
}
}
| 1,030 | 29.323529 | 100 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/NPathTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import java.math.BigInteger;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
import net.sourceforge.pmd.test.AbstractMetricTestRule;
/**
* @author Clément Fournier
*/
public class NPathTestRule extends AbstractMetricTestRule<BigInteger> {
public NPathTestRule() {
super(JavaMetrics.NPATH);
}
@Override
protected String violationMessage(Node node, BigInteger result) {
return AllMetricsTest.formatJavaMessage(node, result, super.violationMessage(node, result));
}
@Override
protected BigInteger parseReportLevel(String value) {
return new BigInteger(value);
}
@Override
protected BigInteger defaultReportLevel() {
return BigInteger.ZERO;
}
}
| 919 | 23.864865 | 100 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/impl/TccTestRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.impl;
import net.sourceforge.pmd.lang.java.metrics.JavaMetrics;
/**
* @author Clément Fournier
* @since 6.0.0
*/
public class TccTestRule extends JavaDoubleMetricTestRule {
public TccTestRule() {
super(JavaMetrics.TIGHT_CLASS_COHESION);
}
}
| 398 | 20 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/testdata/MetricsVisitorTestData.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.testdata;
/**
* Test data for the metrics visitor
*
* @author Clément Fournier
*/
public class MetricsVisitorTestData {
public String x;
private String y;
protected String z;
String t;
public MetricsVisitorTestData() {
}
private MetricsVisitorTestData(String x) {
}
public String getX() {
return x;
}
public String getY() {
return y;
}
public void setX(String n) {
x = n;
}
public void setY(String n) {
y = n;
}
public static class NestedClass {
public NestedClass() {
}
public void nestedMethod1() {
}
}
public void mymethod1() {
}
private void mymethod2() {
}
protected static void mystatic1() {
}
private static void mystatic2(String k) {
}
private static void mystatic2(String k, String l) {
}
}
| 1,042 | 12.723684 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/testdata/SetterDetection.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.testdata;
import org.apache.commons.lang3.mutable.MutableInt;
/**
* @author Clément Fournier
*/
public class SetterDetection {
private int value;
private double speed;
private MutableInt mutX;
private boolean bool;
public void setValue(int x) {
value = x;
}
public void value(int x) {
value = x > 0 ? x : -x;
}
public void speed(int x) {
mutX.setValue(x);
}
public void mutX(int x) {
mutX.increment();
}
public void bool(int value) {
this.value = value;
}
}
| 699 | 16.948718 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/metrics/testdata/GetterDetection.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.metrics.testdata;
import org.apache.commons.lang3.mutable.MutableInt;
/**
* @author Clément Fournier
*/
public class GetterDetection {
private int value;
private double speed;
private MutableInt mutX;
private boolean bool;
public int getValue() {
return value;
}
public boolean isBool() {
return bool;
}
public int value() {
return value;
}
/* public double speedModified() {
return speed * 12 + 1;
}
public int mutableInt() {
return mutX.getValue();
}
public MutableInt theMutable() {
return mutX;
}
public int mutableIntIf() {
if (mutX == null) {
return 0;
} else {
return mutX.getValue();
}
}
public int mutableIntConditional() {
return mutX == null ? 0 : mutX.getValue();
}
*/
}
| 1,016 | 15.95 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/XPathRuleTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
import net.sourceforge.pmd.lang.rule.xpath.internal.DeprecatedAttrLogger;
import net.sourceforge.pmd.lang.rule.xpath.internal.SaxonXPathRuleQuery;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* @author daniels
*/
class XPathRuleTest {
private XPathRule makeXPath(String expression) {
return JavaParsingHelper.DEFAULT.newXpathRule(expression);
}
@Test
void testPluginname() {
XPathRule rule = makeXPath("//VariableDeclaratorId[string-length(@Name) < 3]");
rule.setMessage("{0}");
Report report = getReportForTestString(rule, TEST1);
RuleViolation rv = report.getViolations().get(0);
assertEquals("a", rv.getDescription());
}
@Test
void testXPathMultiProperty() throws Exception {
XPathRule rule = makeXPath("//VariableDeclaratorId[@Name=$forbiddenNames]");
rule.setMessage("Avoid vars");
PropertyDescriptor<List<String>> varDescriptor
= PropertyFactory.stringListProperty("forbiddenNames")
.desc("Forbidden names")
.defaultValues("forbid1", "forbid2")
.delim('$')
.build();
rule.definePropertyDescriptor(varDescriptor);
Report report = getReportForTestString(rule, TEST3);
assertEquals(2, report.getViolations().size());
}
@Test
void testVariables() throws Exception {
XPathRule rule = makeXPath("//VariableDeclaratorId[@Name=$var]");
rule.setMessage("Avoid vars");
PropertyDescriptor<String> varDescriptor =
PropertyFactory.stringProperty("var").desc("Test var").defaultValue("").build();
rule.definePropertyDescriptor(varDescriptor);
rule.setProperty(varDescriptor, "fiddle");
Report report = getReportForTestString(rule, TEST2);
RuleViolation rv = report.getViolations().get(0);
assertEquals(3, rv.getBeginLine());
}
@Test
void testFnPrefixOnSaxon() throws Exception {
XPathRule rule = makeXPath("//VariableDeclaratorId[fn:matches(@Name, 'fiddle')]");
Report report = getReportForTestString(rule, TEST2);
RuleViolation rv = report.getViolations().get(0);
assertEquals(3, rv.getBeginLine());
}
@Test
void testNoFnPrefixOnSaxon() {
XPathRule rule = makeXPath("//VariableDeclaratorId[matches(@Name, 'fiddle')]");
Report report = getReportForTestString(rule, TEST2);
RuleViolation rv = report.getViolations().get(0);
assertEquals(3, rv.getBeginLine());
}
@Test
void testSimpleQueryIsRuleChain() {
// ((/)/descendant::element(Q{}VariableDeclaratorId))[matches(convertUntyped(data(@Name)), "fiddle", "")]
assertIsRuleChain("//VariableDeclaratorId[matches(@Name, 'fiddle')]");
}
@Test
void testSimpleQueryIsRuleChain2() {
// docOrder(((/)/descendant-or-self::node())/(child::element(ClassOrInterfaceType)[typeIs("java.util.Vector")]))
assertIsRuleChain("//ClassOrInterfaceType[pmd-java:typeIs('java.util.Vector')]");
}
private void assertIsRuleChain(String xpath) {
XPathRule rule = makeXPath(xpath);
try (LanguageProcessor proc = JavaParsingHelper.DEFAULT.newProcessor()) {
rule.initialize(proc);
assertTrue(rule.getTargetSelector().isRuleChain(), "Not recognized as a rulechain query: " + xpath);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Following sibling check: See https://sourceforge.net/p/pmd/bugs/1209/
*
* @throws Exception any error
*/
@Test
void testFollowingSibling() throws Exception {
final String source = "public interface dummy extends Foo, Bar, Baz {}";
ASTCompilationUnit cu = JavaParsingHelper.DEFAULT.parse(source);
String xpath = "//ExtendsList/ClassOrInterfaceType/following-sibling::ClassOrInterfaceType";
SaxonXPathRuleQuery xpathRuleQuery = new SaxonXPathRuleQuery(xpath,
XPathVersion.DEFAULT,
new HashMap<>(),
XPathHandler.noFunctionDefinitions(),
DeprecatedAttrLogger.noop());
List<Node> nodes = xpathRuleQuery.evaluate(cu);
assertEquals(2, nodes.size());
assertEquals("Bar", ((JavaNode) nodes.get(0)).getText().toString());
assertEquals("Baz", ((JavaNode) nodes.get(1)).getText().toString());
}
private static Report getReportForTestString(Rule r, String test) {
return JavaParsingHelper.DEFAULT.executeRule(r, test);
}
private static final String TEST1 = "public class Foo {\n"
+ " int a;\n"
+ "}";
private static final String TEST2 = "public class Foo {\n"
+ " int faddle;\n"
+ " int fiddle;\n"
+ "}";
private static final String TEST3 = "public class Foo {\n"
+ " int forbid1; int forbid2; int forbid1$forbid2;\n"
+ "}";
}
| 6,175 | 36.658537 | 120 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/DummyJavaRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
/**
* @author Clément Fournier
*/
public class DummyJavaRule extends AbstractJavaRule {
public void apply(Node node, RuleContext ctx) {
}
public static class DummyRuleOneViolationPerFile extends DummyJavaRule {
@Override
public void apply(Node node, RuleContext ctx) {
ctx.addViolation(node);
}
}
public static class DummyRulePrintsVars extends DummyJavaRule {
@Override
public void apply(Node node, RuleContext ctx) {
((JavaNode) node).jjtAccept(this, ctx);
}
@Override
public Object visit(ASTVariableDeclaratorId node, Object data) {
asCtx(data).addViolation(node, node.getName());
return super.visit(node, data);
}
}
}
| 1,108 | 24.790698 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/security/InsecureCryptoIvTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.security;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class InsecureCryptoIvTest extends PmdRuleTst {
// no additional unit tests
}
| 278 | 22.25 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/security/HardCodedCryptoKeyTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.security;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class HardCodedCryptoKeyTest extends PmdRuleTst {
// no additional unit tests
}
| 280 | 22.416667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/documentation/UncommentedEmptyMethodBodyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.documentation;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UncommentedEmptyMethodBodyTest extends PmdRuleTst {
// no additional unit tests
}
| 294 | 23.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentRequiredTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.documentation;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CommentRequiredTest extends PmdRuleTst {
@Test
void allCommentTypesIgnored() {
CommentRequiredRule rule = new CommentRequiredRule();
assertNull(rule.dysfunctionReason(), "By default, the rule should be functional");
List<PropertyDescriptor<?>> propertyDescriptors = getProperties(rule);
// remove deprecated properties
propertyDescriptors.removeIf(property -> property.description().startsWith("Deprecated!"));
for (PropertyDescriptor<?> property : propertyDescriptors) {
setPropertyValue(rule, property, "Ignored");
}
assertNotNull(rule.dysfunctionReason(), "All properties are ignored, rule should be dysfunctional");
// now, try out combinations: only one of the properties is required.
for (PropertyDescriptor<?> property : propertyDescriptors) {
setPropertyValue(rule, property, "Required");
assertNull(rule.dysfunctionReason(),
"The property " + property.name() + " is set to required, the rule should be functional.");
setPropertyValue(rule, property, "Ignored");
}
}
private static List<PropertyDescriptor<?>> getProperties(Rule rule) {
List<PropertyDescriptor<?>> result = new ArrayList<>();
for (PropertyDescriptor<?> property : rule.getPropertyDescriptors()) {
if (property != Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR
&& property != Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR) {
result.add(property);
}
}
return result;
}
private static <T> void setPropertyValue(Rule rule, PropertyDescriptor<T> property, String value) {
rule.setProperty(property, property.valueFrom(value));
}
}
| 2,290 | 37.830508 | 111 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/documentation/UncommentedEmptyConstructorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.documentation;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UncommentedEmptyConstructorTest extends PmdRuleTst {
// no additional unit tests
}
| 295 | 23.666667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.documentation;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CommentSizeTest extends PmdRuleTst {
// no additional unit tests
}
| 279 | 22.333333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentContentTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.documentation;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CommentContentTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/DoubleCheckedLockingTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DoubleCheckedLockingTest extends PmdRuleTst {
// no additional unit tests
}
| 289 | 23.166667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/DoNotUseThreadsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DoNotUseThreadsTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/UseNotifyAllInsteadOfNotifyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UseNotifyAllInsteadOfNotifyTest extends PmdRuleTst {
// no additional unit tests
}
| 296 | 23.75 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/UseConcurrentHashMapTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UseConcurrentHashMapTest extends PmdRuleTst {
// no additional unit tests
}
| 289 | 23.166667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/UnsynchronizedStaticFormatterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UnsynchronizedStaticFormatterTest extends PmdRuleTst {
// no additional unit tests
}
| 298 | 23.916667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/NonThreadSafeSingletonTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NonThreadSafeSingletonTest extends PmdRuleTst {
// no additional unit tests
}
| 291 | 23.333333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/DontCallThreadRunTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DontCallThreadRunTest extends PmdRuleTst {
// Used by DontCallThreadRun test cases
public static class TestThread extends Thread {
@Override
public void run() {
System.out.println("test");
}
}
}
| 452 | 24.166667 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/AvoidThreadGroupTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidThreadGroupTest extends PmdRuleTst {
// Used by AvoidThreadGroup test cases
public static class ThreadGroup {
}
}
| 341 | 21.8 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/AvoidSynchronizedAtMethodLevelTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidSynchronizedAtMethodLevelTest extends PmdRuleTst {
// no additional unit tests
}
| 299 | 24 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/multithreading/AvoidUsingVolatileTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.multithreading;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidUsingVolatileTest extends PmdRuleTst {
// no additional unit tests
}
| 287 | 23 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/AvoidFieldNameMatchingMethodNameTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidFieldNameMatchingMethodNameTest extends PmdRuleTst {
// no additional unit tests
}
| 297 | 23.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/AssignmentToNonFinalStaticTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AssignmentToNonFinalStaticTest extends PmdRuleTst {
// no additional unit tests
}
| 291 | 23.333333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloneMethodMustBePublicTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CloneMethodMustBePublicTest extends PmdRuleTst {
// no additional unit tests
}
| 288 | 23.083333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/DoNotExtendJavaLangThrowableTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class DoNotExtendJavaLangThrowableTest extends PmdRuleTst {
// no additional unit tests
}
| 293 | 23.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/FinalizeDoesNotCallSuperFinalizeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class FinalizeDoesNotCallSuperFinalizeTest extends PmdRuleTst {
// no additional unit tests
}
| 297 | 23.833333 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/JUnitStaticSuiteTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class JUnitStaticSuiteTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/SuspiciousHashcodeMethodNameTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class SuspiciousHashcodeMethodNameTest extends PmdRuleTst {
// no additional unit tests
}
| 293 | 23.5 | 79 | java |
pmd | pmd-master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/errorprone/MissingStaticMethodInNonInstantiatableClassTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class MissingStaticMethodInNonInstantiatableClassTest extends PmdRuleTst {
// no additional unit tests
}
| 308 | 24.75 | 79 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.