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-modelica/src/main/java/net/sourceforge/pmd/lang/modelica/resolver/ModelicaClassScope.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.modelica.resolver;
/**
* A lexical scope corresponding to a Modelica class.
*/
public final class ModelicaClassScope extends AbstractModelicaScope {
private final ModelicaClassDeclaration classDeclaration;
ModelicaClassScope(ModelicaClassDeclaration declaration) {
classDeclaration = declaration;
classDeclaration.setOwnScope(this);
}
public ModelicaClassType getClassDeclaration() {
return classDeclaration;
}
@Override
public void resolveLexically(ResolutionContext result, CompositeName name) throws Watchdog.CountdownException {
InternalModelicaResolverApi.resolveFurtherNameComponents(classDeclaration, result, name);
if (classDeclaration.isEncapsulated()) {
getRoot().resolveBuiltin(result, name);
} else {
((AbstractModelicaScope) getParent()).resolveLexically(result, name);
}
}
@Override
public String getRepresentation() {
return "Class:" + classDeclaration.getSimpleTypeName();
}
String getFullyQualifiedClassName() {
if (getParent() instanceof ModelicaClassScope) {
return ((ModelicaClassScope) getParent()).getFullyQualifiedClassName() + "." + classDeclaration.getSimpleTypeName();
} else {
return ((ModelicaSourceFileScope) getParent()).getFileFQCN();
}
}
}
| 1,490 | 32.133333 | 128 | java |
pmd | pmd-master/pmd-modelica/src/main/java/net/sourceforge/pmd/lang/modelica/resolver/ModelicaComponentDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.modelica.resolver;
import net.sourceforge.pmd.lang.modelica.ast.ASTComponentClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTComponentDeclaration;
import net.sourceforge.pmd.lang.modelica.ast.ASTConditionAttribute;
import net.sourceforge.pmd.lang.modelica.ast.ASTConstantClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTDeclaration;
import net.sourceforge.pmd.lang.modelica.ast.ASTDiscreteClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTFlowClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTInputClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTName;
import net.sourceforge.pmd.lang.modelica.ast.ASTOutputClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTParameterClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTSimpleName;
import net.sourceforge.pmd.lang.modelica.ast.ASTStreamClause;
import net.sourceforge.pmd.lang.modelica.ast.ASTTypePrefix;
import net.sourceforge.pmd.lang.modelica.ast.ASTTypeSpecifier;
public class ModelicaComponentDeclaration extends AbstractModelicaDeclaration implements ModelicaDeclaration {
public enum ComponentKind {
FLOW("flow"),
STREAM("stream"),
NOTHING_SPECIAL("");
private String name;
ComponentKind(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public enum ComponentVariability {
DISCRETE("discrete"),
PARAMETER("parameter"),
CONSTANT("constant"),
CONTINUOUS("continuous");
private String name;
ComponentVariability(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public enum ComponentCausality {
INPUT("input"),
OUTPUT("output"),
ACAUSAL("acausal");
private String name;
ComponentCausality(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
private ModelicaClassScope containingScope;
private ComponentKind kind;
private ComponentVariability variability;
private ComponentCausality causality;
private final ASTName typeName;
private ResolutionResult<ModelicaType> typeCandidates;
private final String declarationName;
private final ASTConditionAttribute condition;
public ModelicaComponentDeclaration(ASTComponentDeclaration node) {
declarationName = node.getFirstChildOfType(ASTDeclaration.class).getFirstChildOfType(ASTSimpleName.class).getImage();
condition = node.getFirstChildOfType(ASTConditionAttribute.class);
ASTComponentClause declarationRoot = node.getFirstParentOfType(ASTComponentClause.class);
ASTTypePrefix prefixes = declarationRoot.getFirstChildOfType(ASTTypePrefix.class);
parseTypePrefix(prefixes);
typeName = declarationRoot
.getFirstChildOfType(ASTTypeSpecifier.class)
.getFirstChildOfType(ASTName.class);
}
void setContainingScope(ModelicaClassScope scope) {
containingScope = scope;
}
@Override
public ModelicaClassScope getContainingScope() {
return containingScope;
}
private void parseTypePrefix(ASTTypePrefix prefix) {
if (prefix.getFirstChildOfType(ASTFlowClause.class) != null) {
kind = ComponentKind.FLOW;
} else if (prefix.getFirstChildOfType(ASTStreamClause.class) != null) {
kind = ComponentKind.STREAM;
} else {
kind = ComponentKind.NOTHING_SPECIAL;
}
if (prefix.getFirstChildOfType(ASTDiscreteClause.class) != null) {
variability = ComponentVariability.DISCRETE;
} else if (prefix.getFirstChildOfType(ASTParameterClause.class) != null) {
variability = ComponentVariability.PARAMETER;
} else if (prefix.getFirstChildOfType(ASTConstantClause.class) != null) {
variability = ComponentVariability.CONSTANT;
} else {
variability = ComponentVariability.CONTINUOUS;
}
if (prefix.getFirstChildOfType(ASTInputClause.class) != null) {
causality = ComponentCausality.INPUT;
} else if (prefix.getFirstChildOfType(ASTOutputClause.class) != null) {
causality = ComponentCausality.OUTPUT;
} else {
causality = ComponentCausality.ACAUSAL;
}
}
public ASTConditionAttribute getCondition() {
return condition;
}
/**
* Whether this component is declared as <code>flow</code>, <code>stream</code> or nothing special.
*/
public ComponentKind getKind() {
return kind;
}
/**
* Whether this component is a constant, a parameter, a discrete or a continuous variable.
*/
public ComponentVariability getVariability() {
return variability;
}
/**
* Whether this component is input, output or acausal.
*/
public ComponentCausality getCausality() {
return causality;
}
@Override
public String getSimpleDeclarationName() {
return declarationName;
}
@Override
public String getDescriptiveName() {
return declarationName;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (kind != null) {
sb.append(kind.toString());
sb.append(' ');
}
if (variability != null) {
sb.append(variability.toString());
sb.append(' ');
}
if (causality != null) {
sb.append(causality.toString());
sb.append(' ');
}
sb.append(typeName);
sb.append(' ');
sb.append(declarationName);
return sb.toString();
}
public ResolutionResult<ModelicaType> getTypeCandidates() {
if (typeCandidates == null) {
ResolutionContext ctx = ResolutionState.forComponentReference().createContext();
try {
getContainingScope().resolveLexically(ctx, typeName.getCompositeName());
} catch (Watchdog.CountdownException e) {
ctx.markTtlExceeded();
}
typeCandidates = ctx.getTypes();
}
return typeCandidates;
}
@Override
void resolveFurtherNameComponents(ResolutionContext result, CompositeName name) throws Watchdog.CountdownException {
if (name.isEmpty()) {
result.addCandidate(this);
return;
}
ResolutionResult<ModelicaType> resolvedType = getTypeCandidates();
for (ModelicaType decl: resolvedType.getBestCandidates()) {
((AbstractModelicaDeclaration) decl).resolveFurtherNameComponents(result, name);
}
result.markHidingPoint();
for (ModelicaType decl: resolvedType.getHiddenCandidates()) {
((AbstractModelicaDeclaration) decl).resolveFurtherNameComponents(result, name);
}
}
}
| 7,195 | 31.858447 | 125 | java |
pmd | pmd-master/pmd-modelica/src/main/java/net/sourceforge/pmd/lang/modelica/resolver/ResolutionContext.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.modelica.resolver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.annotation.InternalApi;
@InternalApi
public class ResolutionContext {
private final ResolutionState state;
private final List<ResolvableEntity> bestCandidates = new ArrayList<>();
private final List<ResolvableEntity> hiddenCandidates = new ArrayList<>();
private boolean ttlExceeded = false;
private boolean isCollectingHidden = false;
ResolutionContext(ResolutionState ctx) {
state = ctx;
}
public ResolutionState getState() {
return state;
}
public void watchdogTick() throws Watchdog.CountdownException {
state.tick();
}
public void addCandidate(ResolvableEntity candidate) {
if (isCollectingHidden) {
hiddenCandidates.add(candidate);
} else {
bestCandidates.add(candidate);
}
}
/**
* Marks the corresponding resolution process as timed out.
*
* Usually, this method is called after catching `Watchdog.CountdownException`.
*/
void markTtlExceeded() {
ttlExceeded = true;
}
/**
* Mark previously resolved declarations (if any) as more important than the subsequent ones.
*
* It is correct to call this method even at the point when nothing is resolved yet.
* If there is something resolved so far, the subsequent declarations will be considered as hidden.
* If there is nothing resolved so far, the call is ignored.
*/
public void markHidingPoint() {
if (!bestCandidates.isEmpty()) {
isCollectingHidden = true;
}
}
void accumulate(ResolutionResult result) {
bestCandidates.addAll(result.getBestCandidates());
hiddenCandidates.addAll(result.getHiddenCandidates());
}
private static class Result<A extends ResolvableEntity> implements ResolutionResult<A> {
private final List<A> bestCandidates = new ArrayList<>();
private final List<A> hiddenCandidates = new ArrayList<>();
private final boolean timedOut;
Result(Class<A> tpe, List<?> best, List<?> hidden, boolean timedOut) {
for (Object b: best) {
if (tpe.isInstance(b)) {
bestCandidates.add((A) b);
}
}
for (Object h: hidden) {
if (tpe.isInstance(h)) {
hiddenCandidates.add((A) h);
}
}
this.timedOut = timedOut;
}
@Override
public List<A> getBestCandidates() {
return Collections.unmodifiableList(bestCandidates);
}
@Override
public List<A> getHiddenCandidates() {
return Collections.unmodifiableList(hiddenCandidates);
}
@Override
public boolean isUnresolved() {
return bestCandidates.isEmpty();
}
@Override
public boolean isClashed() {
return bestCandidates.size() > 1;
}
@Override
public boolean hasHiddenResults() {
return !hiddenCandidates.isEmpty();
}
@Override
public boolean wasTimedOut() {
return timedOut;
}
}
public ResolutionResult<ModelicaType> getTypes() {
return new Result<>(ModelicaType.class, bestCandidates, hiddenCandidates, ttlExceeded);
}
public ResolutionResult<ModelicaDeclaration> getDeclaration() {
return new Result<>(ModelicaDeclaration.class, bestCandidates, hiddenCandidates, ttlExceeded);
}
public <T extends ResolvableEntity> ResolutionResult<T> get(Class<T> clazz) {
return new Result<>(clazz, bestCandidates, hiddenCandidates, ttlExceeded);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Resolved[");
sb.append(bestCandidates.size());
sb.append('/');
sb.append(hiddenCandidates.size());
sb.append(']');
return sb.toString();
}
}
| 4,233 | 29.028369 | 103 | java |
pmd | pmd-master/pmd-modelica/src/main/java/net/sourceforge/pmd/cpd/ModelicaLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.modelica.ModelicaLanguageModule;
public class ModelicaLanguage extends AbstractLanguage {
public ModelicaLanguage() {
super(ModelicaLanguageModule.NAME, ModelicaLanguageModule.TERSE_NAME, new ModelicaTokenizer(), ModelicaLanguageModule.EXTENSIONS);
}
}
| 425 | 29.428571 | 138 | java |
pmd | pmd-master/pmd-modelica/src/main/java/net/sourceforge/pmd/cpd/ModelicaTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.cpd.token.JavaCCTokenFilter;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.modelica.ast.ModelicaTokenKinds;
public class ModelicaTokenizer extends JavaCCTokenizer {
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return ModelicaTokenKinds.newTokenManager(sourceCode);
}
@Override
protected JavaCCTokenFilter getTokenFilter(TokenManager<JavaccToken> tokenManager) {
return new ModelicaTokenFilter(tokenManager);
}
public static class ModelicaTokenFilter extends JavaCCTokenFilter {
private boolean discardingWithinAndImport = false;
private boolean discardingAnnotation = false;
ModelicaTokenFilter(TokenManager<JavaccToken> tokenManager) {
super(tokenManager);
}
private void skipWithinAndImport(JavaccToken currentToken) {
final int type = currentToken.kind;
if (type == ModelicaTokenKinds.IMPORT || type == ModelicaTokenKinds.WITHIN) {
discardingWithinAndImport = true;
} else if (discardingWithinAndImport && type == ModelicaTokenKinds.SC) {
discardingWithinAndImport = false;
}
}
private void skipAnnotation(JavaccToken currentToken) {
final int type = currentToken.kind;
if (type == ModelicaTokenKinds.ANNOTATION) {
discardingAnnotation = true;
} else if (discardingAnnotation && type == ModelicaTokenKinds.SC) {
discardingAnnotation = false;
}
}
@Override
protected void analyzeToken(JavaccToken currentToken) {
skipWithinAndImport(currentToken);
skipAnnotation(currentToken);
}
@Override
protected boolean isLanguageSpecificDiscarding() {
return discardingWithinAndImport || discardingAnnotation;
}
}
}
| 2,281 | 34.107692 | 89 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/RuleSetFactoryTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
// no additional tests yet
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/LanguageVersionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin;
import java.util.Arrays;
import java.util.Collection;
import net.sourceforge.pmd.AbstractLanguageVersionTest;
class LanguageVersionTest extends AbstractLanguageVersionTest {
static Collection<TestDescriptor> data() {
return Arrays.asList(
new TestDescriptor(KotlinLanguageModule.NAME, KotlinLanguageModule.TERSE_NAME, "1.8",
getLanguage(KotlinLanguageModule.NAME).getDefaultVersion()));
}
}
| 576 | 27.85 | 101 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinParsingHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.jetbrains.annotations.NotNull;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.kotlin.KotlinLanguageModule;
/**
*
*/
public class KotlinParsingHelper extends BaseParsingHelper<KotlinParsingHelper, KotlinParser.KtKotlinFile> {
public static final KotlinParsingHelper DEFAULT = new KotlinParsingHelper(Params.getDefault());
public KotlinParsingHelper(@NotNull Params params) {
super(KotlinLanguageModule.NAME, KotlinParser.KtKotlinFile.class, params);
}
@NotNull
@Override
protected KotlinParsingHelper clone(@NotNull Params params) {
return new KotlinParsingHelper(params);
}
}
| 818 | 26.3 | 108 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/ast/BaseKotlinTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.NodePrintersKt;
/**
*
*/
public class BaseKotlinTreeDumpTest extends BaseTreeDumpTest {
public BaseKotlinTreeDumpTest() {
super(NodePrintersKt.getSimpleNodePrinter(), ".kt");
}
@NonNull
@Override
public KotlinParsingHelper getParser() {
return KotlinParsingHelper.DEFAULT.withResourceContext(getClass(), "testdata");
}
}
| 660 | 23.481481 | 87 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinParserTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.junit.jupiter.api.Test;
/**
*
*/
class KotlinParserTests extends BaseKotlinTreeDumpTest {
@Test
void testSimpleKotlin() {
doTest("Simple");
}
}
| 314 | 14.75 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/rule/errorprone/OverrideBothEqualsAndHashcodeTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class OverrideBothEqualsAndHashcodeTest extends PmdRuleTst {
// no additional unit tests
}
| 295 | 23.666667 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/rule/bestpractices/FunctionNameTooShortTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class FunctionNameTooShortTest extends PmdRuleTst {
// no additional unit tests
}
| 290 | 23.25 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/test/java/net/sourceforge/pmd/cpd/KotlinTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class KotlinTokenizerTest extends CpdTextComparisonTest {
KotlinTokenizerTest() {
super(".kt");
}
@Override
protected String getResourcePrefix() {
return "../lang/kotlin/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new KotlinTokenizer();
}
@Test
void testComments() {
doTest("comment");
}
@Test
void testIncrement() {
doTest("increment");
}
@Test
void testImportsIgnored() {
doTest("imports");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
}
| 884 | 17.061224 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/AbstractKotlinRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinVisitor;
import net.sourceforge.pmd.lang.rule.AbstractVisitorRule;
public abstract class AbstractKotlinRule extends AbstractVisitorRule {
protected AbstractKotlinRule() {
// inheritance constructor
}
@Override
public abstract KotlinVisitor<RuleContext, ?> buildVisitor();
}
| 521 | 25.1 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/KotlinLanguageModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.List;
import net.sourceforge.pmd.annotation.Experimental;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* Language Module for Kotlin
*
* <p>Note: Kotlin support is considered an experimental feature. The AST structure might change.</p>
*/
@Experimental
public class KotlinLanguageModule extends SimpleLanguageModuleBase {
/** The name. */
public static final String NAME = "Kotlin";
/** The terse name. */
public static final String TERSE_NAME = "kotlin";
@InternalApi
public static final List<String> EXTENSIONS = listOf("kt", "ktm");
/**
* Create a new instance of Kotlin Language Module.
*/
public KotlinLanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME)
.extensions(EXTENSIONS)
.addVersion("1.6")
.addVersion("1.7")
.addDefaultVersion("1.8"),
new KotlinHandler());
}
}
| 1,274 | 28.651163 | 101 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/KotlinHandler.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin;
import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.kotlin.ast.PmdKotlinParser;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
public class KotlinHandler extends AbstractPmdLanguageVersionHandler {
private static final XPathHandler XPATH_HANDLER = XPathHandler.noFunctionDefinitions();
@Override
public XPathHandler getXPathHandler() {
return XPATH_HANDLER;
}
@Override
public Parser getParser() {
return new PmdKotlinParser();
}
}
| 718 | 25.62963 | 91 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrNode;
/**
* Supertype of all kotlin nodes.
*/
public interface KotlinNode extends AntlrNode<KotlinNode> {
}
| 298 | 20.357143 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinVisitorBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import net.sourceforge.pmd.lang.ast.AstVisitorBase;
/**
* Base class for kotlin visitors.
*/
public abstract class KotlinVisitorBase<P, R> extends AstVisitorBase<P, R> implements KotlinVisitor<P, R> {
}
| 341 | 21.8 | 107 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinErrorNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.Token;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrErrorNode;
public final class KotlinErrorNode extends BaseAntlrErrorNode<KotlinNode> implements KotlinNode {
KotlinErrorNode(Token token) {
super(token);
}
}
| 404 | 21.5 | 97 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinTerminalNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.Token;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrTerminalNode;
public final class KotlinTerminalNode extends BaseAntlrTerminalNode<KotlinNode> implements KotlinNode {
KotlinTerminalNode(Token token) {
super(token);
}
@Override
public @NonNull String getText() {
String constImage = KotlinParser.DICO.getConstantImageOfToken(getFirstAntlrToken());
return constImage == null ? getFirstAntlrToken().getText() : constImage;
}
@Override
public String getXPathNodeName() {
return KotlinParser.DICO.getXPathNameOfToken(getFirstAntlrToken().getType());
}
@Override
public <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof KotlinVisitor) {
return ((KotlinVisitor<? super P, ? extends R>) visitor).visitKotlinNode(this, data);
}
return super.acceptVisitor(visitor, data);
}
}
| 1,223 | 27.465116 | 103 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinNameDictionary.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.Vocabulary;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrNameDictionary;
final class KotlinNameDictionary extends AntlrNameDictionary {
KotlinNameDictionary(Vocabulary vocab, String[] ruleNames) {
super(vocab, ruleNames);
}
@Override
protected @Nullable String nonAlphaNumName(String name) {
// todo
return super.nonAlphaNumName(name);
}
}
| 619 | 23.8 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/PmdKotlinParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrBaseParser;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtKotlinFile;
/**
* Adapter for the KotlinParser.
*/
public final class PmdKotlinParser extends AntlrBaseParser<KotlinNode, KtKotlinFile> {
@Override
protected KtKotlinFile parse(final Lexer lexer, ParserTask task) {
KotlinParser parser = new KotlinParser(new CommonTokenStream(lexer));
return parser.kotlinFile().makeAstInfo(task);
}
@Override
protected Lexer getLexer(final CharStream source) {
return new KotlinLexer(source);
}
}
| 864 | 27.833333 | 86 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinInnerNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.ParserRuleContext;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrInnerNode;
abstract class KotlinInnerNode extends BaseAntlrInnerNode<KotlinNode> implements KotlinNode {
KotlinInnerNode(ParserRuleContext parent, int invokingStateNumber) {
super(parent, invokingStateNumber);
}
@Override
public <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof KotlinVisitor) {
// some of the generated antlr nodes have no accept method...
return ((KotlinVisitor<? super P, ? extends R>) visitor).visitKotlinNode(this, data);
}
return visitor.visitNode(this, data);
}
@Override // override to make visible in package
protected PmdAsAntlrInnerNode<KotlinNode> asAntlrNode() {
return super.asAntlrNode();
}
@Override
public String getXPathNodeName() {
return KotlinParser.DICO.getXPathNameOfRule(getRuleIndex());
}
}
| 1,192 | 30.394737 | 97 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/ast/KotlinRootNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.ast;
import org.antlr.v4.runtime.ParserRuleContext;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtKotlinFile;
// package private base class
abstract class KotlinRootNode extends KotlinInnerNode implements RootNode {
private AstInfo<KtKotlinFile> astInfo;
KotlinRootNode(ParserRuleContext parent, int invokingStateNumber) {
super(parent, invokingStateNumber);
}
@Override
public AstInfo<KtKotlinFile> getAstInfo() {
return astInfo;
}
KtKotlinFile makeAstInfo(ParserTask task) {
KtKotlinFile me = (KtKotlinFile) this;
this.astInfo = new AstInfo<>(task, me);
return me;
}
}
| 937 | 25.8 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/rule/errorprone/OverrideBothEqualsAndHashcodeRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.rule.errorprone;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.kotlin.AbstractKotlinRule;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtClassDeclaration;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtClassMemberDeclaration;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtClassMemberDeclarations;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtDeclaration;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinParser.KtFunctionDeclaration;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinTerminalNode;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinVisitor;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinVisitorBase;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
public class OverrideBothEqualsAndHashcodeRule extends AbstractKotlinRule {
private static final Visitor INSTANCE = new Visitor();
@Override
public KotlinVisitor<RuleContext, ?> buildVisitor() {
return INSTANCE;
}
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forTypes(KtClassMemberDeclarations.class);
}
private static final class Visitor extends KotlinVisitorBase<RuleContext, Void> {
@Override
public Void visitClassMemberDeclarations(KtClassMemberDeclarations node, RuleContext data) {
List<KtFunctionDeclaration> functions = node.children(KtClassMemberDeclaration.class)
.children(KtDeclaration.class)
.children(KtFunctionDeclaration.class)
.toList();
boolean hasEqualMethod = functions.stream().filter(this::isEqualsMethod).count() == 1L;
boolean hasHashCodeMethod = functions.stream().filter(this::isHashCodeMethod).count() == 1L;
if (hasEqualMethod ^ hasHashCodeMethod) {
data.addViolation(node.ancestors(KtClassDeclaration.class).first());
}
return super.visitClassMemberDeclarations(node, data);
}
private boolean isEqualsMethod(KtFunctionDeclaration fun) {
String name = getFunctionName(fun);
int arity = getArity(fun);
return "equals".equals(name) && hasOverrideModifier(fun) && arity == 1;
}
private boolean isHashCodeMethod(KtFunctionDeclaration fun) {
String name = getFunctionName(fun);
int arity = getArity(fun);
return "hashCode".equals(name) && hasOverrideModifier(fun) && arity == 0;
}
private String getFunctionName(KtFunctionDeclaration fun) {
return fun.simpleIdentifier().children(KotlinTerminalNode.class).first().getText();
}
private boolean hasOverrideModifier(KtFunctionDeclaration fun) {
return fun.modifiers().descendants(KotlinTerminalNode.class)
.any(t -> "override".equals(t.getText()));
}
private int getArity(KtFunctionDeclaration fun) {
return fun.functionValueParameters().functionValueParameter().size();
}
}
}
| 3,295 | 39.195122 | 104 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/lang/kotlin/rule/xpath/internal/BaseKotlinXPathFunction.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.kotlin.rule.xpath.internal;
import net.sourceforge.pmd.lang.kotlin.KotlinLanguageModule;
import net.sourceforge.pmd.lang.rule.xpath.impl.AbstractXPathFunctionDef;
abstract class BaseKotlinXPathFunction extends AbstractXPathFunctionDef {
protected BaseKotlinXPathFunction(String localName) {
super(localName, KotlinLanguageModule.TERSE_NAME);
}
}
| 486 | 29.4375 | 79 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/cpd/KotlinTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.cpd.impl.AntlrTokenizer;
import net.sourceforge.pmd.cpd.token.AntlrTokenFilter;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrToken;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrTokenManager;
import net.sourceforge.pmd.lang.kotlin.ast.KotlinLexer;
/**
* The Kotlin Tokenizer
*/
public class KotlinTokenizer extends AntlrTokenizer {
@Override
protected Lexer getLexerForSource(CharStream charStream) {
return new KotlinLexer(charStream);
}
@Override
protected AntlrTokenFilter getTokenFilter(final AntlrTokenManager tokenManager) {
return new KotlinTokenFilter(tokenManager);
}
/**
* The {@link KotlinTokenFilter} extends the {@link AntlrTokenFilter} to discard
* Kotlin-specific tokens.
* <p>
* By default, it discards package and import statements, and
* enables annotation-based CPD suppression.
* </p>
*/
private static class KotlinTokenFilter extends AntlrTokenFilter {
private boolean discardingPackageAndImport = false;
private boolean discardingNL = false;
/* default */ KotlinTokenFilter(final AntlrTokenManager tokenManager) {
super(tokenManager);
}
@Override
protected void analyzeToken(final AntlrToken currentToken) {
skipPackageAndImport(currentToken);
skipNewLines(currentToken);
}
private void skipPackageAndImport(final AntlrToken currentToken) {
final int type = currentToken.getKind();
if (type == KotlinLexer.PACKAGE || type == KotlinLexer.IMPORT) {
discardingPackageAndImport = true;
} else if (discardingPackageAndImport && (type == KotlinLexer.SEMICOLON || type == KotlinLexer.NL)) {
discardingPackageAndImport = false;
}
}
private void skipNewLines(final AntlrToken currentToken) {
discardingNL = currentToken.getKind() == KotlinLexer.NL;
}
@Override
protected boolean isLanguageSpecificDiscarding() {
return discardingPackageAndImport || discardingNL;
}
}
}
| 2,373 | 31.972222 | 113 | java |
pmd | pmd-master/pmd-kotlin/src/main/java/net/sourceforge/pmd/cpd/KotlinLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.kotlin.KotlinLanguageModule;
/**
* Language implementation for Kotlin
*/
public class KotlinLanguage extends AbstractLanguage {
/**
* Creates a new Kotlin Language instance.
*/
public KotlinLanguage() {
super(KotlinLanguageModule.NAME, KotlinLanguageModule.TERSE_NAME, new KotlinTokenizer(), KotlinLanguageModule.EXTENSIONS);
}
}
| 519 | 23.761905 | 130 | java |
pmd | pmd-master/pmd-php/src/main/java/net/sourceforge/pmd/cpd/PHPLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* Language implementation for PHP
*/
public class PHPLanguage extends AbstractLanguage {
/**
* Creates a new PHP Language instance.
*/
public PHPLanguage() {
super("PHP", "php", new PHPTokenizer(), ".php", ".class");
}
}
| 381 | 19.105263 | 79 | java |
pmd | pmd-master/pmd-php/src/main/java/net/sourceforge/pmd/cpd/PHPTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.List;
/**
* Simple tokenizer for PHP.
*/
public class PHPTokenizer implements Tokenizer {
@Override
public void tokenize(SourceCode tokens, Tokens tokenEntries) {
List<String> code = tokens.getCode();
for (int i = 0; i < code.size(); i++) {
String currentLine = code.get(i);
for (int j = 0; j < currentLine.length(); j++) {
char tok = currentLine.charAt(j);
if (!Character.isWhitespace(tok) && tok != '{' && tok != '}' && tok != ';') {
tokenEntries.add(new TokenEntry(String.valueOf(tok), tokens.getFileName(), i + 1));
}
}
}
tokenEntries.add(TokenEntry.getEOF());
}
}
| 861 | 28.724138 | 103 | java |
pmd | pmd-master/pmd-cs/src/test/java/net/sourceforge/pmd/cpd/CsTokenizerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
import net.sourceforge.pmd.lang.ast.TokenMgrError;
class CsTokenizerTest extends CpdTextComparisonTest {
CsTokenizerTest() {
super(".cs");
}
@Override
protected String getResourcePrefix() {
return "../lang/cs/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
CsTokenizer tok = new CsTokenizer();
tok.setProperties(properties);
return tok;
}
@Test
void testSimpleClass() {
doTest("simpleClass");
}
@Test
void testSimpleClassMethodMultipleLines() {
doTest("simpleClassMethodMultipleLines");
}
@Test
void testStrings() {
doTest("strings");
}
@Test
void testOpenString() {
assertThrows(TokenMgrError.class, () -> doTest("unlexable_string"));
}
@Test
void testCommentsIgnored1() {
doTest("comments");
}
@Test
void testIgnoreBetweenSpecialComments() {
doTest("specialComments");
}
@Test
void testOperators() {
doTest("operatorsAndStuff");
}
@Test
void testLineNumberAfterMultilineString() {
doTest("strings");
}
@Test
void testDoNotIgnoreUsingDirectives() {
doTest("usingDirectives");
}
@Test
void testIgnoreUsingDirectives() {
doTest("usingDirectives", "_ignored", ignoreUsings());
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
@Test
void testLongListsOfNumbersAreNotIgnored() {
doTest("listOfNumbers");
}
@Test
void testLongListsOfNumbersAreIgnored() {
doTest("listOfNumbers", "_ignored", skipLiteralSequences());
}
@Test
void testCSharp7And8Additions() {
doTest("csharp7And8Additions");
}
@Test
void testAttributesAreNotIgnored() {
doTest("attributes");
}
@Test
void testAttributesAreIgnored() {
doTest("attributes", "_ignored", skipAttributes());
}
private Properties ignoreUsings() {
return properties(true, false, false);
}
private Properties skipLiteralSequences() {
return properties(false, true, false);
}
private Properties skipAttributes() {
return properties(false, false, true);
}
private Properties properties(boolean ignoreUsings, boolean ignoreLiteralSequences, boolean ignoreAttributes) {
Properties properties = new Properties();
properties.setProperty(Tokenizer.IGNORE_USINGS, Boolean.toString(ignoreUsings));
properties.setProperty(Tokenizer.OPTION_IGNORE_LITERAL_SEQUENCES, Boolean.toString(ignoreLiteralSequences));
properties.setProperty(Tokenizer.IGNORE_ANNOTATIONS, Boolean.toString(ignoreAttributes));
return properties;
}
}
| 3,105 | 22.007407 | 116 | java |
pmd | pmd-master/pmd-cs/src/main/java/net/sourceforge/pmd/cpd/CsLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
/**
* Language implementation for C#
*/
public class CsLanguage extends AbstractLanguage {
public CsLanguage() {
this(System.getProperties());
}
public CsLanguage(Properties properties) {
super("C#", "cs", new CsTokenizer(), ".cs");
setProperties(properties);
}
@Override
public final void setProperties(Properties properties) {
CsTokenizer tokenizer = (CsTokenizer) getTokenizer();
tokenizer.setProperties(properties);
}
}
| 650 | 21.448276 | 79 | java |
pmd | pmd-master/pmd-cs/src/main/java/net/sourceforge/pmd/cpd/CsTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.cpd.impl.AntlrTokenizer;
import net.sourceforge.pmd.cpd.token.AntlrTokenFilter;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrToken;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrTokenManager;
import net.sourceforge.pmd.lang.cs.ast.CSharpLexer;
/**
* The C# tokenizer.
*/
public class CsTokenizer extends AntlrTokenizer {
private boolean ignoreUsings = false;
private boolean ignoreLiteralSequences = false;
private boolean ignoreAttributes = false;
/**
* Sets the possible options for the C# tokenizer.
*
* @param properties the properties
* @see #IGNORE_USINGS
* @see #OPTION_IGNORE_LITERAL_SEQUENCES
* @see #IGNORE_ANNOTATIONS
*/
public void setProperties(Properties properties) {
ignoreUsings = getBooleanProperty(properties, IGNORE_USINGS);
ignoreLiteralSequences = getBooleanProperty(properties, OPTION_IGNORE_LITERAL_SEQUENCES);
ignoreAttributes = getBooleanProperty(properties, IGNORE_ANNOTATIONS);
}
private boolean getBooleanProperty(final Properties properties, final String property) {
return Boolean.parseBoolean(properties.getProperty(property, Boolean.FALSE.toString()));
}
@Override
protected Lexer getLexerForSource(final CharStream charStream) {
return new CSharpLexer(charStream);
}
@Override
protected AntlrTokenFilter getTokenFilter(final AntlrTokenManager tokenManager) {
return new CsTokenFilter(tokenManager, ignoreUsings, ignoreLiteralSequences, ignoreAttributes);
}
/**
* The {@link CsTokenFilter} extends the {@link AntlrTokenFilter} to discard
* C#-specific tokens.
* <p>
* By default, it enables annotation-based CPD suppression.
* If the --ignoreUsings flag is provided, using directives are filtered out.
* </p>
*/
private static class CsTokenFilter extends AntlrTokenFilter {
private enum UsingState {
KEYWORD, // just encountered the using keyword
IDENTIFIER, // just encountered an identifier or var keyword
}
private final boolean ignoreUsings;
private final boolean ignoreLiteralSequences;
private final boolean ignoreAttributes;
private boolean discardingUsings = false;
private boolean discardingNL = false;
private boolean isDiscardingAttribute = false;
private AntlrToken discardingLiteralsUntil = null;
private boolean discardCurrent = false;
CsTokenFilter(final AntlrTokenManager tokenManager, boolean ignoreUsings, boolean ignoreLiteralSequences, boolean ignoreAttributes) {
super(tokenManager);
this.ignoreUsings = ignoreUsings;
this.ignoreLiteralSequences = ignoreLiteralSequences;
this.ignoreAttributes = ignoreAttributes;
}
@Override
protected void analyzeToken(final AntlrToken currentToken) {
skipNewLines(currentToken);
}
@Override
protected void analyzeTokens(final AntlrToken currentToken, final Iterable<AntlrToken> remainingTokens) {
discardCurrent = false;
skipUsingDirectives(currentToken, remainingTokens);
skipLiteralSequences(currentToken, remainingTokens);
skipAttributes(currentToken);
}
private void skipUsingDirectives(final AntlrToken currentToken, final Iterable<AntlrToken> remainingTokens) {
if (ignoreUsings) {
final int type = currentToken.getKind();
if (type == CSharpLexer.USING && isUsingDirective(remainingTokens)) {
discardingUsings = true;
} else if (type == CSharpLexer.SEMICOLON && discardingUsings) {
discardingUsings = false;
discardCurrent = true;
}
}
}
private boolean isUsingDirective(final Iterable<AntlrToken> remainingTokens) {
UsingState usingState = UsingState.KEYWORD;
for (final AntlrToken token : remainingTokens) {
final int type = token.getKind();
if (usingState == UsingState.KEYWORD) {
// The previous token was a using keyword.
switch (type) {
case CSharpLexer.STATIC:
// Definitely a using directive.
// Example: using static System.Math;
return true;
case CSharpLexer.VAR:
// Definitely a using statement.
// Example: using var font1 = new Font("Arial", 10.0f);
return false;
case CSharpLexer.OPEN_PARENS:
// Definitely a using statement.
// Example: using (var font1 = new Font("Arial", 10.0f);
return false;
case CSharpLexer.IDENTIFIER:
// This is either a type for a using statement or an alias for a using directive.
// Example (directive): using Project = PC.MyCompany.Project;
// Example (statement): using Font font1 = new Font("Arial", 10.0f);
usingState = UsingState.IDENTIFIER;
break;
default:
// Some unknown construct?
return false;
}
} else if (usingState == UsingState.IDENTIFIER) {
// The previous token was an identifier.
switch (type) {
case CSharpLexer.ASSIGNMENT:
// Definitely a using directive.
// Example: using Project = PC.MyCompany.Project;
return true;
case CSharpLexer.IDENTIFIER:
// Definitely a using statement.
// Example: using Font font1 = new Font("Arial", 10.0f);
return false;
case CSharpLexer.DOT:
// This should be considered part of the same type; revert to previous state.
// Example (directive): using System.Text;
// Example (statement): using System.Drawing.Font font1 = new Font("Arial", 10.0f);
usingState = UsingState.KEYWORD;
break;
case CSharpLexer.SEMICOLON:
// End of using directive.
return true;
default:
// Some unknown construct?
return false;
}
}
}
return false;
}
private void skipNewLines(final AntlrToken currentToken) {
discardingNL = currentToken.getKind() == CSharpLexer.NL;
}
private void skipAttributes(final AntlrToken currentToken) {
if (ignoreAttributes) {
switch (currentToken.getKind()) {
case CSharpLexer.OPEN_BRACKET:
// Start of an attribute.
isDiscardingAttribute = true;
break;
case CSharpLexer.CLOSE_BRACKET:
// End of an attribute.
isDiscardingAttribute = false;
discardCurrent = true;
break;
default:
// Skip any other token.
break;
}
}
}
private void skipLiteralSequences(final AntlrToken currentToken, final Iterable<AntlrToken> remainingTokens) {
if (ignoreLiteralSequences) {
final int type = currentToken.getKind();
if (isDiscardingLiterals()) {
if (currentToken == discardingLiteralsUntil) { // NOPMD - intentional check for reference equality
discardingLiteralsUntil = null;
discardCurrent = true;
}
} else if (type == CSharpLexer.OPEN_BRACE) {
final AntlrToken finalToken = findEndOfSequenceOfLiterals(remainingTokens);
discardingLiteralsUntil = finalToken;
}
}
}
private AntlrToken findEndOfSequenceOfLiterals(final Iterable<AntlrToken> remainingTokens) {
boolean seenLiteral = false;
int braceCount = 0;
for (final AntlrToken token : remainingTokens) {
switch (token.getKind()) {
case CSharpLexer.BIN_INTEGER_LITERAL:
case CSharpLexer.CHARACTER_LITERAL:
case CSharpLexer.HEX_INTEGER_LITERAL:
case CSharpLexer.INTEGER_LITERAL:
case CSharpLexer.REAL_LITERAL:
seenLiteral = true;
break; // can be skipped; continue to the next token
case CSharpLexer.COMMA:
break; // can be skipped; continue to the next token
case CSharpLexer.OPEN_BRACE:
braceCount++;
break; // curly braces are allowed, as long as they're balanced
case CSharpLexer.CLOSE_BRACE:
braceCount--;
if (braceCount < 0) {
// end of the list; skip all contents
return seenLiteral ? token : null;
} else {
// curly braces are not yet balanced; continue to the next token
break;
}
default:
// some other token than the expected ones; this is not a sequence of literals
return null;
}
}
return null;
}
public boolean isDiscardingLiterals() {
return discardingLiteralsUntil != null;
}
@Override
protected boolean isLanguageSpecificDiscarding() {
return discardingUsings || discardingNL || isDiscardingAttribute || isDiscardingLiterals() || discardCurrent;
}
}
}
| 10,598 | 41.396 | 141 | java |
pmd | pmd-master/pmd-matlab/src/test/java/net/sourceforge/pmd/cpd/MatlabTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class MatlabTokenizerTest extends CpdTextComparisonTest {
MatlabTokenizerTest() {
super(".m");
}
@Override
protected String getResourcePrefix() {
return "../lang/matlab/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new MatlabTokenizer();
}
@Test
void testLongSample() {
doTest("sample-matlab");
}
@Test
void testIgnoreBetweenSpecialComments() {
doTest("specialComments");
}
@Test
void testComments() {
doTest("comments");
}
@Test
void testBlockComments() {
doTest("multilineComments");
}
@Test
void testQuestionMark() {
doTest("questionMark");
}
@Test
void testDoubleQuotedStrings() {
doTest("doubleQuotedStrings");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
}
| 1,173 | 17.061538 | 79 | java |
pmd | pmd-master/pmd-matlab/src/main/java/net/sourceforge/pmd/cpd/MatlabLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* Defines the Language module for Matlab
*/
public class MatlabLanguage extends AbstractLanguage {
/**
* Creates a new instance of {@link MatlabLanguage} with the default
* extensions for matlab files.
*/
public MatlabLanguage() {
super("Matlab", "matlab", new MatlabTokenizer(), ".m");
}
}
| 456 | 21.85 | 79 | java |
pmd | pmd-master/pmd-matlab/src/main/java/net/sourceforge/pmd/cpd/MatlabTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.matlab.ast.MatlabTokenKinds;
/**
* The Matlab Tokenizer.
*/
public class MatlabTokenizer extends JavaCCTokenizer {
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return MatlabTokenKinds.newTokenManager(sourceCode);
}
}
| 656 | 27.565217 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyLanguage;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.DEPRECATED;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.NAME;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class RuleSetFactoryTest extends RulesetFactoryTestBase {
@Test
void testRuleSetFileName() {
RuleSet rs = new RuleSetLoader().loadFromString("dummyRuleset.xml", EMPTY_RULESET);
assertEquals("dummyRuleset.xml", rs.getFileName());
rs = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/TestRuleset1.xml");
assertEquals(rs.getFileName(), "net/sourceforge/pmd/TestRuleset1.xml", "wrong RuleSet file name");
}
@Test
void testRefs() {
RuleSet rs = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/TestRuleset1.xml");
assertNotNull(rs.getRuleByName("TestRuleRef"));
}
@Test
void testExtendedReferences() throws Exception {
InputStream in = new ResourceLoader().loadClassPathResourceAsStream("net/sourceforge/pmd/rulesets/reference-ruleset.xml");
assertNotNull(in, "Test ruleset not found - can't continue with test!");
in.close();
RuleSet rs = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/rulesets/reference-ruleset.xml");
// added by referencing a complete ruleset (TestRuleset1.xml)
assertNotNull(rs.getRuleByName("MockRule1"));
assertNotNull(rs.getRuleByName("MockRule2"));
assertNotNull(rs.getRuleByName("MockRule3"));
assertNotNull(rs.getRuleByName("TestRuleRef"));
// added by specific reference
assertNotNull(rs.getRuleByName("TestRule"));
// this is from TestRuleset2.xml, but not referenced
assertNull(rs.getRuleByName("TestRule2Ruleset2"));
Rule mockRule3 = rs.getRuleByName("MockRule3");
assertEquals("Overridden message", mockRule3.getMessage());
assertEquals(2, mockRule3.getPriority().getPriority());
Rule mockRule2 = rs.getRuleByName("MockRule2");
assertEquals("Just combine them!", mockRule2.getMessage());
// assert that MockRule2 is only once added to the ruleset, so that it
// really
// overwrites the configuration inherited from TestRuleset1.xml
assertNotNull(rs.getRuleByName("MockRule2"));
Rule mockRule1 = rs.getRuleByName("MockRule1");
assertNotNull(mockRule1);
PropertyDescriptor<?> prop = mockRule1.getPropertyDescriptor("testIntProperty");
Object property = mockRule1.getProperty(prop);
assertEquals("5", String.valueOf(property));
// included from TestRuleset3.xml
assertNotNull(rs.getRuleByName("Ruleset3Rule2"));
// excluded from TestRuleset3.xml
assertNull(rs.getRuleByName("Ruleset3Rule1"));
// overridden to 5
Rule ruleset4Rule1 = rs.getRuleByName("Ruleset4Rule1");
assertNotNull(ruleset4Rule1);
assertEquals(5, ruleset4Rule1.getPriority().getPriority());
assertNotNull(rs.getRuleByName("Ruleset4Rule1"));
// priority overridden for whole TestRuleset4 group
Rule ruleset4Rule2 = rs.getRuleByName("Ruleset4Rule2");
assertNotNull(ruleset4Rule2);
assertEquals(2, ruleset4Rule2.getPriority().getPriority());
}
@Test
void testRuleSetNotFound() {
assertThrows(RuleSetLoadException.class, () -> new RuleSetLoader().loadFromResource("fooooo"));
}
@Test
void testCreateEmptyRuleSet() {
RuleSet rs = loadRuleSet(EMPTY_RULESET);
assertEquals("Custom ruleset", rs.getName());
assertEquals(0, rs.size());
}
@Test
void testSingleRule() {
RuleSet rs = loadRuleSet(SINGLE_RULE);
assertEquals(1, rs.size());
Rule r = rs.getRules().iterator().next();
assertEquals("MockRuleName", r.getName());
assertEquals("net.sourceforge.pmd.lang.rule.MockRule", r.getRuleClass());
assertEquals("avoid the mock rule", r.getMessage());
}
@Test
void testSingleRuleEmptyRef() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSet(SINGLE_RULE_EMPTY_REF);
assertEquals(1, rs.size());
Rule r = rs.getRules().iterator().next();
assertEquals("MockRuleName", r.getName());
assertEquals("net.sourceforge.pmd.lang.rule.MockRule", r.getRuleClass());
assertEquals("avoid the mock rule", r.getMessage());
});
assertThat(log, containsString("Empty ref attribute"));
}
@Test
void testMultipleRules() {
RuleSet rs = loadRuleSet(rulesetXml(
dummyRule(attrs -> attrs.put(NAME, "MockRuleName1")),
dummyRule(attrs -> attrs.put(NAME, "MockRuleName2"))
));
assertEquals(2, rs.size());
Set<String> expected = new HashSet<>();
expected.add("MockRuleName1");
expected.add("MockRuleName2");
for (Rule rule : rs.getRules()) {
assertTrue(expected.contains(rule.getName()));
}
}
@Test
void testSingleRuleWithPriority() {
Rule rule = loadFirstRule(rulesetXml(
rule(
dummyRuleDefAttrs(),
priority("3")
)
));
assertEquals(RulePriority.MEDIUM, rule.getPriority());
}
@Test
void testProps() {
Rule r = loadFirstRule(PROPERTIES);
assertEquals("bar", r.getProperty(r.getPropertyDescriptor("fooString")));
assertEquals(3, r.getProperty(r.getPropertyDescriptor("fooInt")));
assertEquals(true, r.getProperty(r.getPropertyDescriptor("fooBoolean")));
assertEquals(3.0d, (Double) r.getProperty(r.getPropertyDescriptor("fooDouble")), 0.05);
assertNull(r.getPropertyDescriptor("BuggleFish"));
assertNotSame(r.getDescription().indexOf("testdesc2"), -1);
}
@Test
void testStringMultiPropertyDefaultDelimiter() {
Rule r = loadFirstRule(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ruleset name=\"the ruleset\">\n <description>Desc</description>\n"
+ " <rule name=\"myRule\" message=\"Do not place to this package. Move to \n{0} package/s instead.\" \n"
+ "class=\"net.sourceforge.pmd.lang.rule.XPathRule\" language=\"dummy\">\n"
+ " <description>Please move your class to the right folder(rest \nfolder)</description>\n"
+ " <priority>2</priority>\n <properties>\n <property name=\"packageRegEx\""
+ " value=\"com.aptsssss|com.abc\" \ntype=\"List[String]\" "
+ "description=\"valid packages\"/>\n </properties></rule></ruleset>");
Object propValue = r.getProperty(r.getPropertyDescriptor("packageRegEx"));
assertEquals(Arrays.asList("com.aptsssss", "com.abc"), propValue);
}
@Test
void testStringMultiPropertyDelimiter() {
Rule r = loadFirstRule("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n "
+ " <description>ruleset desc</description>\n "
+ "<rule name=\"myRule\" message=\"Do not place to this package. Move to \n{0} package/s"
+ " instead.\" \n"
+ "class=\"net.sourceforge.pmd.lang.rule.XPathRule\" language=\"dummy\">\n"
+ " <description>Please move your class to the right folder(rest \nfolder)</description>\n"
+ " <priority>2</priority>\n <properties>\n <property name=\"packageRegEx\""
+ " value=\"com.aptsssss,com.abc\" \ntype=\"List[String]\" delimiter=\",\" "
+ "description=\"valid packages\"/>\n"
+ " </properties></rule>" + "</ruleset>");
Object propValue = r.getProperty(r.getPropertyDescriptor("packageRegEx"));
assertEquals(Arrays.asList("com.aptsssss", "com.abc"), propValue);
}
/**
* Verifies that empty values for properties are possible. Empty values can be used to disable a property.
* However, the semantic depends on the concrete rule implementation.
*
* @see <a href="https://github.com/pmd/pmd/issues/4279">[java] TestClassWithoutTestCases - can not set test pattern to empty #4279</a>
*/
@Test
void testEmptyStringProperty() {
Rule r = loadFirstRule("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ruleset name=\"test\">\n "
+ " <description>ruleset desc</description>\n "
+ "<rule name=\"myRule\" message=\"Do not place to this package. Move to \n{0} package/s"
+ " instead.\" \n" + "class=\"net.sourceforge.pmd.RuleWithProperties\" language=\"dummy\">\n"
+ " <description>Please move your class to the right folder(rest \nfolder)</description>\n"
+ " <priority>2</priority>\n <properties>\n <property name=\"stringProperty\""
+ " value=\"\" />\n"
+ " </properties></rule>" + "</ruleset>");
PropertyDescriptor<String> prop = (PropertyDescriptor<String>) r.getPropertyDescriptor("stringProperty");
String value = r.getProperty(prop);
assertEquals("", value);
}
@Test
void testRuleSetWithDeprecatedRule() {
RuleSet rs = loadRuleSet("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"ruleset\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule deprecated=\"true\" ref=\"rulesets/dummy/basic.xml/DummyBasicMockRule\"/>"
+ "</ruleset>");
assertEquals(1, rs.getRules().size());
Rule rule = rs.getRuleByName("DummyBasicMockRule");
assertNotNull(rule);
}
/**
* This is an example of a category (built-in) ruleset, which contains a rule, that has been renamed.
* This means: a rule definition for "NewName" and a rule reference "OldName", that is deprecated
* and exists for backwards compatibility.
*
* <p>When loading this ruleset at a whole, we shouldn't get a deprecation warning. The deprecated
* rule reference should be ignored, so at the end, we only have the new rule name in the ruleset.
* This is because the deprecated reference points to a rule in the same ruleset.
*
*/
@Test
void testRuleSetWithDeprecatedButRenamedRule() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule deprecated=\"true\" ref=\"NewName\" name=\"OldName\"/>"
+ " <rule name=\"NewName\" message=\"m\" class=\"net.sourceforge.pmd.lang.rule.XPathRule\" language=\"dummy\">"
+ " <description>d</description>\n" + " <priority>2</priority>\n" + " </rule>"
+ "</ruleset>");
assertEquals(1, rs.getRules().size());
Rule rule = rs.getRuleByName("NewName");
assertNotNull(rule);
assertNull(rs.getRuleByName("OldName"));
});
verifyNoWarnings();
}
/**
* This is an example of a category (built-in) ruleset, which contains a rule, that has been renamed.
* This means: a rule definition for "NewName" and a rule reference "OldName", that is deprecated
* and exists for backwards compatibility.
*
* <p>When loading this ruleset at a whole for generating the documentation, we should still
* include the deprecated rule reference, so that we can create a nice documentation.
*
*/
@Test
void testRuleSetWithDeprecatedRenamedRuleForDoc() {
RuleSetLoader loader = new RuleSetLoader().includeDeprecatedRuleReferences(true);
RuleSet rs = loader.loadFromString("",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule deprecated=\"true\" ref=\"NewName\" name=\"OldName\"/>"
+ " <rule name=\"NewName\" message=\"m\" class=\"net.sourceforge.pmd.lang.rule.XPathRule\" language=\"dummy\">"
+ " <description>d</description>\n"
+ " <priority>2</priority>\n"
+ " </rule>"
+ "</ruleset>");
assertEquals(2, rs.getRules().size());
assertNotNull(rs.getRuleByName("NewName"));
assertNotNull(rs.getRuleByName("OldName"));
}
/**
* This is an example of a custom user ruleset, that references a rule, that has been renamed.
* The user should get a deprecation warning.
*/
@Test
void testRuleSetReferencesADeprecatedRenamedRule() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule ref=\"rulesets/dummy/basic.xml/OldNameOfDummyBasicMockRule\"/>" + "</ruleset>");
assertEquals(1, rs.getRules().size());
Rule rule = rs.getRuleByName("OldNameOfDummyBasicMockRule");
assertNotNull(rule);
});
verifyFoundAWarningWithMessage(
containing("Use Rule name rulesets/dummy/basic.xml/DummyBasicMockRule "
+ "instead of the deprecated Rule name rulesets/dummy/basic.xml/OldNameOfDummyBasicMockRule")
);
}
/**
* This is an example of a custom user ruleset, that references a complete (e.g. category) ruleset,
* that contains a renamed (deprecated) rule and two normal rules and one deprecated rule.
*
* <p>
* The user should not get a deprecation warning for the whole ruleset,
* since not all rules are deprecated in the referenced ruleset. Although the referenced ruleset contains
* a deprecated rule, there should be no warning about it, because all deprecated rules are ignored,
* if a whole ruleset is referenced.
*
* <p>
* In the end, we should get all non-deprecated rules of the referenced ruleset.
*
*/
@Test
void testRuleSetReferencesRulesetWithADeprecatedRenamedRule() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule ref=\"rulesets/dummy/basic.xml\"/>" + "</ruleset>");
assertEquals(2, rs.getRules().size());
assertNotNull(rs.getRuleByName("DummyBasicMockRule"));
assertNotNull(rs.getRuleByName("SampleXPathRule"));
});
verifyNoWarnings();
}
/**
* This is an example of a custom user ruleset, that references a complete (e.g. category) ruleset,
* that contains a renamed (deprecated) rule and two normal rules and one deprecated rule. The deprecated
* rule is excluded.
*
* <p>
* The user should not get a deprecation warning for the whole ruleset,
* since not all rules are deprecated in the referenced ruleset. Since the deprecated rule is excluded,
* there should be no deprecation warning at all, although the deprecated ruleset would have been
* excluded by default (without explictly excluding it).
*
* <p>
* In the end, we should get all non-deprecated rules of the referenced ruleset.
*
*/
@Test
void testRuleSetReferencesRulesetWithAExcludedDeprecatedRule() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ruleset name=\"test\">\n"
+ " <description>ruleset desc</description>\n"
+ " <rule ref=\"rulesets/dummy/basic.xml\"><exclude name=\"DeprecatedRule\"/></rule>"
+ "</ruleset>");
assertEquals(2, rs.getRules().size());
assertNotNull(rs.getRuleByName("DummyBasicMockRule"));
assertNotNull(rs.getRuleByName("SampleXPathRule"));
});
assertTrue(log.isEmpty());
}
/**
* This is an example of a custom user ruleset, that references a complete (e.g. category) ruleset,
* that contains a renamed (deprecated) rule and two normal rules and one deprecated rule.
* There is a exclusion of a rule, that no longer exists.
*
* <p>
* The user should not get a deprecation warning for the whole ruleset,
* since not all rules are deprecated in the referenced ruleset.
* Since the rule to be excluded doesn't exist, there should be a warning about that.
*
*/
@Test
void testRuleSetReferencesRulesetWithAExcludedNonExistingRule() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
rulesetXml(
rulesetRef("rulesets/dummy/basic.xml",
excludeRule("NonExistingRule"))
));
assertEquals(2, rs.getRules().size());
assertNotNull(rs.getRuleByName("DummyBasicMockRule"));
assertNotNull(rs.getRuleByName("SampleXPathRule"));
});
verifyFoundWarningWithMessage(
Mockito.never(),
containing("Discontinue using Rule rulesets/dummy/basic.xml/DeprecatedRule")
);
verifyFoundAWarningWithMessage(containing(
"Exclude pattern 'NonExistingRule' did not match any rule in ruleset"
));
}
/**
* When a custom ruleset references a ruleset that only contains deprecated rules, then this ruleset itself is
* considered deprecated and the user should get a deprecation warning for the ruleset.
*/
@Test
void testRuleSetReferencesDeprecatedRuleset() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
rulesetXml(
rulesetRef("rulesets/dummy/deprecated.xml")
));
assertEquals(2, rs.getRules().size());
assertNotNull(rs.getRuleByName("DummyBasicMockRule"));
assertNotNull(rs.getRuleByName("SampleXPathRule"));
});
verifyFoundAWarningWithMessage(containing(
"The RuleSet rulesets/dummy/deprecated.xml has been deprecated and will be removed in PMD"
));
}
/**
* When a custom ruleset references a ruleset that contains both rules and rule references, that are left
* for backwards compatibility, because the rules have been moved to a different ruleset, then there should be
* no warning about deprecation - since the deprecated rules are not used.
*/
@Test
void testRuleSetReferencesRulesetWithAMovedRule() throws Exception {
SystemLambda.tapSystemErr(() -> {
RuleSet rs = loadRuleSetWithDeprecationWarnings(
rulesetXml(
ruleRef("rulesets/dummy/basic2.xml")
)
);
assertEquals(1, rs.getRules().size());
assertNotNull(rs.getRuleByName("DummyBasic2MockRule"));
});
verifyFoundWarningWithMessage(
Mockito.never(),
containing("Use Rule name rulesets/dummy/basic.xml/DummyBasicMockRule instead of the deprecated Rule name rulesets/dummy/basic2.xml/DummyBasicMockRule")
);
}
@Test
@SuppressWarnings("unchecked")
void testXPath() {
Rule r = loadFirstRule(XPATH);
PropertyDescriptor<String> xpathProperty = (PropertyDescriptor<String>) r.getPropertyDescriptor("xpath");
assertNotNull(xpathProperty, "xpath property descriptor");
assertNotSame(r.getProperty(xpathProperty).indexOf("//Block"), -1);
}
@Test
void testExternalReferenceOverride() {
Rule r = loadFirstRule(REF_OVERRIDE);
assertEquals("TestNameOverride", r.getName());
assertEquals("Test message override", r.getMessage());
assertEquals("Test description override", r.getDescription());
assertEquals(2, r.getExamples().size(), "Test that both example are stored");
assertEquals("Test example override", r.getExamples().get(1));
assertEquals(RulePriority.MEDIUM, r.getPriority());
PropertyDescriptor<?> test2Descriptor = r.getPropertyDescriptor("test2");
assertNotNull(test2Descriptor, "test2 descriptor");
assertEquals("override2", r.getProperty(test2Descriptor));
PropertyDescriptor<?> test3Descriptor = r.getPropertyDescriptor("test3");
assertNotNull(test3Descriptor, "test3 descriptor");
assertEquals("override3", r.getProperty(test3Descriptor));
}
@Test
void testExternalReferenceOverrideNonExistent() {
assertThrows(RuleSetLoadException.class,
() -> loadFirstRule(REF_OVERRIDE_NONEXISTENT));
verifyFoundAnErrorWithMessage(
containing("Cannot set non-existent property 'test4' on rule TestNameOverride")
);
}
@Test
void testReferenceInternalToInternal() {
RuleSet ruleSet = loadRuleSet(REF_INTERNAL_TO_INTERNAL);
Rule rule = ruleSet.getRuleByName("MockRuleName");
assertNotNull(rule, "Could not find Rule MockRuleName");
Rule ruleRef = ruleSet.getRuleByName("MockRuleNameRef");
assertNotNull(ruleRef, "Could not find Rule MockRuleNameRef");
}
@Test
void testReferenceInternalToInternalChain() {
RuleSet ruleSet = loadRuleSet(REF_INTERNAL_TO_INTERNAL_CHAIN);
Rule rule = ruleSet.getRuleByName("MockRuleName");
assertNotNull(rule, "Could not find Rule MockRuleName");
Rule ruleRef = ruleSet.getRuleByName("MockRuleNameRef");
assertNotNull(ruleRef, "Could not find Rule MockRuleNameRef");
Rule ruleRefRef = ruleSet.getRuleByName("MockRuleNameRefRef");
assertNotNull(ruleRefRef, "Could not find Rule MockRuleNameRefRef");
}
@Test
void testReferenceInternalToExternal() {
RuleSet ruleSet = loadRuleSet(REF_INTERNAL_TO_EXTERNAL);
Rule rule = ruleSet.getRuleByName("ExternalRefRuleName");
assertNotNull(rule, "Could not find Rule ExternalRefRuleName");
Rule ruleRef = ruleSet.getRuleByName("ExternalRefRuleNameRef");
assertNotNull(ruleRef, "Could not find Rule ExternalRefRuleNameRef");
}
@Test
void testReferenceInternalToExternalChain() {
RuleSet ruleSet = loadRuleSet(REF_INTERNAL_TO_EXTERNAL_CHAIN);
Rule rule = ruleSet.getRuleByName("ExternalRefRuleName");
assertNotNull(rule, "Could not find Rule ExternalRefRuleName");
Rule ruleRef = ruleSet.getRuleByName("ExternalRefRuleNameRef");
assertNotNull(ruleRef, "Could not find Rule ExternalRefRuleNameRef");
Rule ruleRefRef = ruleSet.getRuleByName("ExternalRefRuleNameRefRef");
assertNotNull(ruleRefRef, "Could not find Rule ExternalRefRuleNameRefRef");
}
@Test
void testReferencePriority() {
RuleSetLoader config = new RuleSetLoader().warnDeprecated(false).enableCompatibility(true);
RuleSetLoader rulesetLoader = config.filterAbovePriority(RulePriority.LOW);
RuleSet ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_INTERNAL_CHAIN);
assertEquals(3, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("MockRuleName"));
assertNotNull(ruleSet.getRuleByName("MockRuleNameRef"));
assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
rulesetLoader = config.filterAbovePriority(RulePriority.MEDIUM_HIGH);
ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_INTERNAL_CHAIN);
assertEquals(2, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("MockRuleNameRef"));
assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
rulesetLoader = config.filterAbovePriority(RulePriority.HIGH);
ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_INTERNAL_CHAIN);
assertEquals(1, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
rulesetLoader = config.filterAbovePriority(RulePriority.LOW);
ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_EXTERNAL_CHAIN);
assertEquals(3, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleName"));
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRef"));
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
rulesetLoader = config.filterAbovePriority(RulePriority.MEDIUM_HIGH);
ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_EXTERNAL_CHAIN);
assertEquals(2, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRef"));
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
rulesetLoader = config.filterAbovePriority(RulePriority.HIGH);
ruleSet = rulesetLoader.loadFromString("", REF_INTERNAL_TO_EXTERNAL_CHAIN);
assertEquals(1, ruleSet.getRules().size(), "Number of Rules");
assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
}
@Test
void testOverridePriorityLoadWithMinimum() {
RuleSetLoader rulesetLoader = new RuleSetLoader().filterAbovePriority(RulePriority.MEDIUM_LOW)
.warnDeprecated(true).enableCompatibility(true);
RuleSet ruleset = rulesetLoader.loadFromResource("net/sourceforge/pmd/rulesets/ruleset-minimum-priority.xml");
// only one rule should remain, since we filter out the other rule by minimum priority
assertEquals(1, ruleset.getRules().size(), "Number of Rules");
// Priority is overridden and applied, rule is missing
assertNull(ruleset.getRuleByName("DummyBasicMockRule"));
// this is the remaining rule
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
// now, load with default minimum priority
rulesetLoader = new RuleSetLoader();
ruleset = rulesetLoader.loadFromResource("net/sourceforge/pmd/rulesets/ruleset-minimum-priority.xml");
assertEquals(2, ruleset.getRules().size(), "Number of Rules");
Rule dummyBasicMockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertEquals(RulePriority.LOW, dummyBasicMockRule.getPriority(), "Wrong Priority");
}
@Test
void testExcludeWithMinimumPriority() {
RuleSetLoader rulesetLoader = new RuleSetLoader().filterAbovePriority(RulePriority.HIGH);
RuleSet ruleset = rulesetLoader
.loadFromResource("net/sourceforge/pmd/rulesets/ruleset-minimum-priority-exclusion.xml");
// no rules should be loaded
assertEquals(0, ruleset.getRules().size(), "Number of Rules");
// now, load with default minimum priority
rulesetLoader = new RuleSetLoader().filterAbovePriority(RulePriority.LOW);
ruleset = rulesetLoader.loadFromResource("net/sourceforge/pmd/rulesets/ruleset-minimum-priority-exclusion.xml");
// only one rule, we have excluded one...
assertEquals(1, ruleset.getRules().size(), "Number of Rules");
// rule is excluded
assertNull(ruleset.getRuleByName("DummyBasicMockRule"));
// this is the remaining rule
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
}
@Test
void testOverrideMessage() {
Rule r = loadFirstRule(REF_OVERRIDE_ORIGINAL_NAME);
assertEquals("TestMessageOverride", r.getMessage());
}
@Test
void testOverrideMessageOneElem() {
Rule r = loadFirstRule(REF_OVERRIDE_ORIGINAL_NAME_ONE_ELEM);
assertEquals("TestMessageOverride", r.getMessage());
}
@Test
void testIncorrectExternalRef() {
assertCannotParse(REF_MISSPELLED_XREF);
}
@Test
void testSetPriority() {
RuleSetLoader rulesetLoader = new RuleSetLoader().filterAbovePriority(RulePriority.MEDIUM_HIGH).warnDeprecated(false);
assertEquals(0, rulesetLoader.loadFromString("", SINGLE_RULE).size());
rulesetLoader = new RuleSetLoader().filterAbovePriority(RulePriority.MEDIUM_LOW).warnDeprecated(false);
assertEquals(1, rulesetLoader.loadFromString("", SINGLE_RULE).size());
}
@Test
void testLanguage() {
Rule r = loadFirstRule(rulesetXml(
dummyRule(
attrs -> attrs.put(SchemaConstants.LANGUAGE, "dummy")
)
));
assertEquals(dummyLanguage(), r.getLanguage());
}
@Test
void testIncorrectLanguage() {
assertCannotParse(rulesetXml(
dummyRule(
attrs -> attrs.put(SchemaConstants.LANGUAGE, "bogus")
)
));
}
@Test
void testIncorrectPriority() {
assertCannotParse(rulesetXml(
dummyRule(
priority("not a priority")
)
));
verifyFoundAnErrorWithMessage(containing("Not a valid priority: 'not a priority'"));
}
@Test
void testMinimumLanguageVersion() {
Rule r = loadFirstRule(rulesetXml(
dummyRule(
attrs -> attrs.put(SchemaConstants.MINIMUM_LANGUAGE_VERSION, "1.4")
)
));
assertEquals(dummyLanguage().getVersion("1.4"),
r.getMinimumLanguageVersion());
}
@Test
void testIncorrectMinimumLanguageVersion() {
assertCannotParse(rulesetXml(
dummyRule(
attrs -> attrs.put(SchemaConstants.MINIMUM_LANGUAGE_VERSION, "bogus")
)
));
verifyFoundAnErrorWithMessage(
containing("valid language version")
.and(containing("'1.0', '1.1', '1.2'")) // and not "dummy 1.0, dummy 1.1, ..."
);
}
@Test
void testIncorrectMinimumLanguageVersionWithLanguageSetInJava() {
assertCannotParse("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ruleset name=\"TODO\">\n"
+ " <description>TODO</description>\n"
+ "\n"
+ " <rule name=\"TODO\"\n"
+ " message=\"TODO\"\n"
+ " class=\"net.sourceforge.pmd.util.FooRuleWithLanguageSetInJava\"\n"
+ " minimumLanguageVersion=\"12\">\n"
+ " <description>TODO</description>\n"
+ " <priority>2</priority>\n"
+ " </rule>\n"
+ "\n"
+ "</ruleset>");
verifyFoundAnErrorWithMessage(
containing("valid language version")
);
}
@Test
void testMaximumLanguageVersion() {
Rule r = loadFirstRule(rulesetXml(
dummyRule(attrs -> attrs.put(SchemaConstants.MAXIMUM_LANGUAGE_VERSION, "1.7"))
));
assertEquals(dummyLanguage().getVersion("1.7"),
r.getMaximumLanguageVersion());
}
@Test
void testIncorrectMaximumLanguageVersion() {
assertCannotParse(rulesetXml(
dummyRule(attrs -> attrs.put(SchemaConstants.MAXIMUM_LANGUAGE_VERSION, "bogus"))
));
verifyFoundAnErrorWithMessage(
containing("valid language version")
.and(containing("'1.0', '1.1', '1.2'"))
);
}
@Test
void testInvertedMinimumMaximumLanguageVersions() {
assertCannotParse(rulesetXml(
dummyRule(
attrs -> {
attrs.put(SchemaConstants.MINIMUM_LANGUAGE_VERSION, "1.7");
attrs.put(SchemaConstants.MAXIMUM_LANGUAGE_VERSION, "1.4");
}
)
));
verifyFoundAnErrorWithMessage(containing("version range"));
}
@Test
void testDirectDeprecatedRule() {
Rule r = loadFirstRule(rulesetXml(
dummyRule(attrs -> attrs.put(DEPRECATED, "true"))
));
assertNotNull(r, "Direct Deprecated Rule");
assertTrue(r.isDeprecated());
}
@Test
void testReferenceToDeprecatedRule() {
Rule r = loadFirstRule(REFERENCE_TO_DEPRECATED_RULE);
assertNotNull(r, "Reference to Deprecated Rule");
assertTrue(r instanceof RuleReference, "Rule Reference");
assertFalse(r.isDeprecated(), "Not deprecated");
assertTrue(((RuleReference) r).getRule().isDeprecated(), "Original Rule Deprecated");
assertEquals(r.getName(), DEPRECATED_RULE_NAME, "Rule name");
}
@Test
void testRuleSetReferenceWithDeprecatedRule() {
RuleSet ruleSet = loadRuleSet(REFERENCE_TO_RULESET_WITH_DEPRECATED_RULE);
assertNotNull(ruleSet, "RuleSet");
assertFalse(ruleSet.getRules().isEmpty(), "RuleSet empty");
// No deprecated Rules should be loaded when loading an entire RuleSet
// by reference - unless it contains only deprecated rules - then all rules would be added
Rule r = ruleSet.getRuleByName(DEPRECATED_RULE_NAME);
assertNull(r, "Deprecated Rule Reference");
for (Rule rule : ruleSet.getRules()) {
assertFalse(rule.isDeprecated(), "Rule not deprecated");
}
}
@Test
void testDeprecatedRuleSetReference() {
RuleSet ruleSet = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/rulesets/ruleset-deprecated.xml");
assertEquals(2, ruleSet.getRules().size());
}
@Test
void testExternalReferences() {
RuleSet rs = loadRuleSet(
rulesetXml(
ruleRef("net/sourceforge/pmd/external-reference-ruleset.xml/MockRule")
)
);
assertEquals(1, rs.size());
assertEquals(MockRule.class.getName(), rs.getRuleByName("MockRule").getRuleClass());
}
@Test
void testIncludeExcludePatterns() {
RuleSet ruleSet = loadRuleSet(INCLUDE_EXCLUDE_RULESET);
assertNotNull(ruleSet.getFileInclusions(), "Include patterns");
assertEquals(2, ruleSet.getFileInclusions().size(), "Include patterns size");
assertEquals("include1", ruleSet.getFileInclusions().get(0).pattern(), "Include pattern #1");
assertEquals("include2", ruleSet.getFileInclusions().get(1).pattern(), "Include pattern #2");
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(3, ruleSet.getFileExclusions().size(), "Exclude patterns size");
assertEquals("exclude1", ruleSet.getFileExclusions().get(0).pattern(), "Exclude pattern #1");
assertEquals("exclude2", ruleSet.getFileExclusions().get(1).pattern(), "Exclude pattern #2");
assertEquals("exclude3", ruleSet.getFileExclusions().get(2).pattern(), "Exclude pattern #3");
}
/**
* Rule reference can't be resolved - ref is used instead of class and the
* class is old (pmd 4.3 and not pmd 5).
*/
@Test
void testBug1202() {
assertCannotParse(
rulesetXml(
ruleRef(
"net.sourceforge.pmd.rules.XPathRule",
priority("1"),
properties(
propertyWithValueAttr("xpath", "//TypeDeclaration"),
propertyWithValueAttr("message", "Foo")
)
)
)
);
}
/**
* See https://sourceforge.net/p/pmd/bugs/1225/
*/
@Test
void testEmptyRuleSetFile() {
RuleSet ruleset = loadRuleSet(
rulesetXml(
excludePattern(".*Test.*")
));
assertEquals(0, ruleset.getRules().size());
}
/**
* See https://github.com/pmd/pmd/issues/782
* Empty ruleset should be interpreted as deprecated.
*/
@Test
void testEmptyRuleSetReferencedShouldNotBeDeprecated() {
RuleSet ruleset = loadRuleSet(
rulesetXml(
ruleRef("rulesets/dummy/empty-ruleset.xml")
)
);
assertEquals(0, ruleset.getRules().size());
verifyNoWarnings();
}
/**
* See https://sourceforge.net/p/pmd/bugs/1231/
*/
@Test
void testWrongRuleNameReferenced() {
assertCannotParse(rulesetXml(
ruleRef("net/sourceforge/pmd/TestRuleset1.xml/ThisRuleDoesNotExist")
));
}
/**
* Unit test for #1312 see https://sourceforge.net/p/pmd/bugs/1312/
*/
@Test
void testRuleReferenceWithNameOverridden() {
RuleSet rs = loadRuleSet("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ruleset xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " name=\"pmd-eclipse\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>PMD Plugin preferences rule set</description>\n"
+ "<rule name=\"OverriddenDummyBasicMockRule\"\n"
+ " ref=\"rulesets/dummy/basic.xml/DummyBasicMockRule\">\n" + "</rule>\n" + "\n"
+ "</ruleset>");
Rule r = rs.getRules().iterator().next();
assertEquals("OverriddenDummyBasicMockRule", r.getName());
RuleReference ruleRef = (RuleReference) r;
assertEquals("DummyBasicMockRule", ruleRef.getRule().getName());
}
/**
* See https://sourceforge.net/p/pmd/bugs/1231/
*
* <p>See https://github.com/pmd/pmd/issues/1978 - with that, it should not be an error anymore.
*
*/
@Test
void testWrongRuleNameExcluded() {
RuleSet ruleset = loadRuleSet("<?xml version=\"1.0\"?>\n" + "<ruleset name=\"Custom ruleset for tests\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Custom ruleset for tests</description>\n"
+ " <rule ref=\"net/sourceforge/pmd/TestRuleset1.xml\">\n"
+ " <exclude name=\"ThisRuleDoesNotExist\"/>\n" + " </rule>\n"
+ "</ruleset>\n");
assertEquals(4, ruleset.getRules().size());
}
/**
* This unit test manifests the current behavior - which might change in the
* future. See #1537.
*
* Currently, if a ruleset is imported twice, the excludes of the first
* import are ignored. Duplicated rules are silently ignored.
*
* @see <a href="https://sourceforge.net/p/pmd/bugs/1537/">#1537 Implement
* strict ruleset parsing</a>
* @see <a href=
* "http://stackoverflow.com/questions/40299075/custom-pmd-ruleset-not-working">stackoverflow
* - custom ruleset not working</a>
*/
@Test
void testExcludeAndImportTwice() {
RuleSet ruleset = loadRuleSet(
rulesetXml(
rulesetRef("rulesets/dummy/basic.xml",
excludeRule("DummyBasicMockRule")
)
)
);
assertNull(ruleset.getRuleByName("DummyBasicMockRule"));
RuleSet ruleset2 = loadRuleSet(
rulesetXml(
rulesetRef("rulesets/dummy/basic.xml",
excludeRule("DummyBasicMockRule")
),
rulesetRef("rulesets/dummy/basic.xml")
)
);
assertNotNull(ruleset2.getRuleByName("DummyBasicMockRule"));
RuleSet ruleset3 = loadRuleSet(
rulesetXml(
rulesetRef("rulesets/dummy/basic.xml"),
rulesetRef("rulesets/dummy/basic.xml",
excludeRule("DummyBasicMockRule")
)
)
);
assertNotNull(ruleset3.getRuleByName("DummyBasicMockRule"));
}
@Test
void testMissingRuleSetNameIsWarning() throws Exception {
SystemLambda.tapSystemErr(() -> {
loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\"?>\n" + "<ruleset \n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Custom ruleset for tests</description>\n"
+ " <rule ref=\"rulesets/dummy/basic.xml\"/>\n"
+ " </ruleset>\n"
);
});
verifyFoundAWarningWithMessage(containing("RuleSet name is missing."));
}
@Test
void testMissingRuleSetDescriptionIsWarning() {
loadRuleSetWithDeprecationWarnings(
"<?xml version=\"1.0\"?>\n" + "<ruleset name=\"then name\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <rule ref=\"rulesets/dummy/basic.xml\"/>\n"
+ " </ruleset>\n"
);
verifyFoundAWarningWithMessage(containing("RuleSet description is missing."));
}
@Test
void testDeprecatedRulesetReferenceProducesWarning() throws Exception {
String log = SystemLambda.tapSystemErr(
() -> loadRuleSetWithDeprecationWarnings(
rulesetXml(
ruleRef("dummy-basic")
)));
System.out.println(log);
verifyFoundAWarningWithMessage(containing(
"Ruleset reference 'dummy-basic' uses a deprecated form, use 'rulesets/dummy/basic.xml' instead"
));
}
private static final String REF_OVERRIDE_ORIGINAL_NAME = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ " <rule \n"
+ "\n"
+ " ref=\"net/sourceforge/pmd/TestRuleset1.xml/MockRule1\" message=\"TestMessageOverride\"> \n"
+ "\n"
+ " </rule>\n"
+ "</ruleset>";
private static final String REF_MISSPELLED_XREF = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ "\n"
+ " <description>testdesc</description>\n"
+ " <rule \n"
+ " ref=\"net/sourceforge/pmd/TestRuleset1.xml/FooMockRule1\"> \n"
+ " </rule>\n"
+ "</ruleset>";
private static final String REF_OVERRIDE_ORIGINAL_NAME_ONE_ELEM = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ " <rule ref=\"net/sourceforge/pmd/TestRuleset1.xml/MockRule1\" message=\"TestMessageOverride\"/> \n"
+ "\n"
+ "</ruleset>";
private static final String REF_OVERRIDE = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ " <rule \n"
+ " ref=\"net/sourceforge/pmd/TestRuleset1.xml/MockRule4\" \n"
+ " name=\"TestNameOverride\" \n"
+ "\n"
+ " message=\"Test message override\"> \n"
+ " <description>Test description override</description>\n"
+ " <example>Test example override</example>\n"
+ " <priority>3</priority>\n"
+ " <properties>\n"
+ " <property name=\"test2\" description=\"test2\" type=\"String\" value=\"override2\"/>\n"
+ " <property name=\"test3\" type=\"String\" description=\"test3\"><value>override3</value></property>\n"
+ "\n"
+ " </properties>\n"
+ " </rule>\n"
+ "</ruleset>";
private static final String REF_OVERRIDE_NONEXISTENT = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ "\n"
+ " <description>testdesc</description>\n"
+ " <rule \n"
+ " ref=\"net/sourceforge/pmd/TestRuleset1.xml/MockRule4\" \n"
+ " name=\"TestNameOverride\" \n"
+ "\n"
+ " message=\"Test message override\"> \n"
+ " <description>Test description override</description>\n"
+ " <example>Test example override</example>\n"
+ " <priority>3</priority>\n"
+ " <properties>\n"
+ " <property name=\"test4\" description=\"test4\" type=\"String\" value=\"new property\"/>\n"
+ " </properties>\n"
+ " </rule>\n"
+ "</ruleset>";
private static final String REF_INTERNAL_TO_INTERNAL = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ "<rule \n"
+ "\n"
+ "language=\"dummy\" \n"
+ "name=\"MockRuleName\" \n"
+ "message=\"avoid the mock rule\" \n"
+ "class=\"net.sourceforge.pmd.lang.rule.MockRule\">\n"
+ "</rule>\n"
+ " <rule ref=\"MockRuleName\" name=\"MockRuleNameRef\"/> \n"
+ "</ruleset>";
private static final String REF_INTERNAL_TO_INTERNAL_CHAIN = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ "<rule \n"
+ "\n"
+ "language=\"dummy\" \n"
+ "name=\"MockRuleName\" \n"
+ "message=\"avoid the mock rule\" \n"
+ "class=\"net.sourceforge.pmd.lang.rule.MockRule\">\n"
+ "</rule>\n"
+ " <rule ref=\"MockRuleName\" name=\"MockRuleNameRef\"><priority>2</priority></rule> \n"
+ " <rule ref=\"MockRuleNameRef\" name=\"MockRuleNameRefRef\"><priority>1</priority></rule> \n"
+ "</ruleset>";
private static final String REF_INTERNAL_TO_EXTERNAL = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ "<rule \n"
+ "\n"
+ "name=\"ExternalRefRuleName\" \n"
+ "ref=\"net/sourceforge/pmd/TestRuleset1.xml/MockRule1\"/>\n"
+ " <rule ref=\"ExternalRefRuleName\" name=\"ExternalRefRuleNameRef\"/> \n"
+ "</ruleset>";
private static final String REF_INTERNAL_TO_EXTERNAL_CHAIN = "<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ " <description>testdesc</description>\n"
+ "<rule \n"
+ "\n"
+ "name=\"ExternalRefRuleName\" \n"
+ "ref=\"net/sourceforge/pmd/TestRuleset2.xml/TestRule\"/>\n"
+ " <rule ref=\"ExternalRefRuleName\" name=\"ExternalRefRuleNameRef\"><priority>2</priority></rule> \n"
+ "\n"
+ " <rule ref=\"ExternalRefRuleNameRef\" name=\"ExternalRefRuleNameRefRef\"><priority>1</priority></rule> \n"
+ "\n"
+ "</ruleset>";
private static final String EMPTY_RULESET = rulesetXml();
private static final String SINGLE_RULE =
rulesetXml(
rule(
dummyRuleDefAttrs(),
priority("3")
)
);
private static final String SINGLE_RULE_EMPTY_REF =
"<?xml version=\"1.0\"?>\n"
+ "<ruleset name=\"test\">\n"
+ "<description>testdesc</description>\n"
+ "<rule \n"
+ "language=\"dummy\" \n"
+ "ref=\"\" \n"
+ "name=\"MockRuleName\" \n"
+ "message=\"avoid the mock rule\" \n"
+ "class=\"net.sourceforge.pmd.lang.rule.MockRule\">\n"
+ "<priority>3</priority>\n"
+ "</rule></ruleset>";
private static final String PROPERTIES =
rulesetXml(
rule(dummyRuleDefAttrs(),
description("testdesc2"),
properties(
"<property name=\"fooBoolean\" description=\"test\" type=\"Boolean\" value=\"true\" />\n",
"<property name=\"fooChar\" description=\"test\" type=\"Character\" value=\"B\" />\n",
"<property name=\"fooInt\" description=\"test\" type=\"Integer\" min=\"1\" max=\"10\" value=\"3\" />",
"<property name=\"fooDouble\" description=\"test\" type=\"Double\" min=\"1.0\" max=\"9.0\" value=\"3.0\" />\n",
"<property name=\"fooString\" description=\"test\" type=\"String\" value=\"bar\" />\n"
))
);
private static final String XPATH =
rulesetXml(
rule(
dummyRuleDefAttrs(),
description("testDesc"),
properties(
"<property name=\"xpath\" description=\"test\" type=\"String\">\n"
+ "<value>\n"
+ "<![CDATA[ //Block ]]>\n"
+ "</value>"
+ "</property>"
)
)
);
// Note: Update this RuleSet name to a different RuleSet with deprecated
// Rules when the Rules are finally removed.
private static final String DEPRECATED_RULE_RULESET_NAME = "net/sourceforge/pmd/TestRuleset1.xml";
// Note: Update this Rule name to a different deprecated Rule when the one
// listed here is finally removed.
private static final String DEPRECATED_RULE_NAME = "MockRule3";
private static final String REFERENCE_TO_DEPRECATED_RULE =
rulesetXml(
ruleRef(DEPRECATED_RULE_RULESET_NAME + "/" + DEPRECATED_RULE_NAME)
);
private static final String REFERENCE_TO_RULESET_WITH_DEPRECATED_RULE =
rulesetXml(
rulesetRef(DEPRECATED_RULE_RULESET_NAME)
);
private static final String INCLUDE_EXCLUDE_RULESET =
rulesetXml(
includePattern("include1"),
includePattern("include2"),
excludePattern("exclude1"),
excludePattern("exclude2"),
excludePattern("exclude3")
);
}
| 52,738 | 42.87604 | 164 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryDuplicatedRuleLoggingTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class RuleSetFactoryDuplicatedRuleLoggingTest extends RulesetFactoryTestBase {
private static final String DIR = "net/sourceforge/pmd/rulesets/duplicatedRuleLoggingTest";
@Test
void duplicatedRuleReferenceShouldWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReference.xml");
assertEquals(1, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.MEDIUM, mockRule.getPriority());
});
assertThat(log, containsString(
"The rule DummyBasicMockRule is referenced multiple times in ruleset 'Custom Rules'. "
+ "Only the last rule configuration is used"));
}
@Test
void duplicatedRuleReferenceWithOverrideShouldNotWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReferenceWithOverride.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertTrue(log.isEmpty());
}
@Test
void duplicatedRuleReferenceWithOverrideBeforeShouldNotWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReferenceWithOverrideBefore.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertTrue(log.isEmpty());
}
@Test
void multipleDuplicates() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "multipleDuplicates.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.MEDIUM_HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertThat(log, containsString("The rule DummyBasicMockRule is referenced multiple times in ruleset 'Custom Rules'. Only the last rule configuration is used."));
assertThat(log, containsString("The ruleset rulesets/dummy/basic.xml is referenced multiple times in ruleset 'Custom Rules'"));
}
}
| 3,393 | 41.962025 | 169 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.PmdCoreTestUtils.setDummyLanguage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
class RuleViolationComparatorTest {
@Test
void testComparator() {
Rule rule1 = setDummyLanguage(new MockRule("name1", "desc", "msg", "rulesetname1"));
Rule rule2 = setDummyLanguage(new MockRule("name2", "desc", "msg", "rulesetname2"));
// RuleViolations created in pre-sorted order
RuleViolation[] expectedOrder = new RuleViolation[12];
int index = 0;
// Different begin line
expectedOrder[index++] = createJavaRuleViolation(rule1, "file1", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule1, "file1", 20, "desc1", 1, 20, 80);
// Different description
expectedOrder[index++] = createJavaRuleViolation(rule1, "file2", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule1, "file2", 10, "desc2", 1, 20, 80);
// Different begin column
expectedOrder[index++] = createJavaRuleViolation(rule1, "file3", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule1, "file3", 10, "desc1", 10, 20, 80);
// Different end line
expectedOrder[index++] = createJavaRuleViolation(rule1, "file4", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule1, "file4", 10, "desc1", 1, 30, 80);
// Different end column
expectedOrder[index++] = createJavaRuleViolation(rule1, "file5", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule1, "file5", 10, "desc1", 1, 20, 90);
// Different rule name
expectedOrder[index++] = createJavaRuleViolation(rule1, "file6", 10, "desc1", 1, 20, 80);
expectedOrder[index++] = createJavaRuleViolation(rule2, "file6", 10, "desc1", 1, 20, 80);
// Randomize
List<RuleViolation> ruleViolations = new ArrayList<>(Arrays.asList(expectedOrder));
long seed = System.nanoTime();
Random random = new Random(seed);
Collections.shuffle(ruleViolations, random);
// Sort
Collections.sort(ruleViolations, RuleViolation.DEFAULT_COMPARATOR);
// Check
int count = 0;
for (int i = 0; i < expectedOrder.length; i++) {
count++;
assertSame(expectedOrder[i], ruleViolations.get(i), "Wrong RuleViolation " + i + ", used seed: " + seed);
}
assertEquals(expectedOrder.length, count, "Missing assertion for every RuleViolation");
}
private RuleViolation createJavaRuleViolation(Rule rule, String fileName, int beginLine, String description,
int beginColumn, int endLine, int endColumn) {
FileLocation loc = FileLocation.range(FileId.fromPathLikeString(fileName), TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn));
return new ParametricRuleViolation(rule, loc, description, Collections.emptyMap());
}
}
| 3,629 | 44.949367 | 148 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyLanguage;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyLanguage2;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyVersion;
import static net.sourceforge.pmd.ReportTestUtil.getReportForRuleSetApply;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
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.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.Report.ProcessingError;
import net.sourceforge.pmd.RuleSet.RuleSetBuilder;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
class RuleSetTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@Test
void testRuleSetRequiresName() {
assertThrows(NullPointerException.class, () ->
new RuleSetBuilder(new Random().nextLong())
.withName(null));
}
@Test
void testRuleSetRequiresDescription() {
assertThrows(NullPointerException.class, () ->
new RuleSetBuilder(new Random().nextLong())
.withName("some name")
.withDescription(null));
}
@Test
void testRuleSetRequiresName2() {
assertThrows(NullPointerException.class, () ->
new RuleSetBuilder(new Random().nextLong()).build());
}
@Test
void testAccessors() {
RuleSet rs = new RuleSetBuilder(new Random().nextLong())
.withFileName("baz")
.withName("foo")
.withDescription("bar")
.build();
assertEquals("baz", rs.getFileName(), "file name mismatch");
assertEquals("foo", rs.getName(), "name mismatch");
assertEquals("bar", rs.getDescription(), "description mismatch");
}
@Test
void testGetRuleByName() {
MockRule mock = new MockRule("name", "desc", "msg", "rulesetname");
RuleSet rs = RuleSet.forSingleRule(mock);
assertEquals(mock, rs.getRuleByName("name"), "unable to fetch rule by name");
}
@Test
void testGetRuleByName2() {
MockRule mock = new MockRule("name", "desc", "msg", "rulesetname");
RuleSet rs = RuleSet.forSingleRule(mock);
assertNull(rs.getRuleByName("FooRule"), "the rule FooRule must not be found!");
}
@Test
void testRuleList() {
MockRule rule = new MockRule("name", "desc", "msg", "rulesetname");
RuleSet ruleset = RuleSet.forSingleRule(rule);
assertEquals(1, ruleset.size(), "Size of RuleSet isn't one.");
Collection<Rule> rules = ruleset.getRules();
Iterator<Rule> i = rules.iterator();
assertTrue(i.hasNext(), "Empty Set");
assertEquals(1, rules.size(), "Returned set of wrong size.");
assertEquals(rule, i.next(), "Rule isn't in ruleset.");
}
private RuleSetBuilder createRuleSetBuilder(String name) {
return new RuleSetBuilder(new Random().nextLong())
.withName(name)
.withDescription("Description for " + name);
}
@Test
void testAddRuleSet() {
RuleSet set1 = createRuleSetBuilder("ruleset1")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
RuleSet set2 = createRuleSetBuilder("ruleset2")
.addRule(new MockRule("name2", "desc", "msg", "rulesetname"))
.addRuleSet(set1)
.build();
assertEquals(2, set2.size(), "ruleset size wrong");
}
@Test
void testAddRuleSetByReferenceBad() {
RuleSet set1 = createRuleSetBuilder("ruleset1")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
assertThrows(RuntimeException.class, () ->
createRuleSetBuilder("ruleset2")
.addRule(new MockRule("name2", "desc", "msg", "rulesetname"))
.addRuleSetByReference(set1, false)
.build());
}
@Test
void testAddRuleSetByReferenceAllRule() {
RuleSet set2 = createRuleSetBuilder("ruleset2")
.withFileName("foo")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.addRule(new MockRule("name2", "desc", "msg", "rulesetname"))
.build();
RuleSet set1 = createRuleSetBuilder("ruleset1")
.addRuleSetByReference(set2, true)
.build();
assertEquals(2, set1.getRules().size(), "wrong rule size");
for (Rule rule : set1.getRules()) {
assertTrue(rule instanceof RuleReference, "not a rule reference");
RuleReference ruleReference = (RuleReference) rule;
assertEquals("foo", ruleReference.getRuleSetReference().getRuleSetFileName(), "wrong ruleset file name");
assertTrue(ruleReference.getRuleSetReference().isAllRules(), "not all rule reference");
}
}
@Test
void testAddRuleSetByReferenceSingleRule() {
RuleSet set2 = createRuleSetBuilder("ruleset2")
.withFileName("foo")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.addRule(new MockRule("name2", "desc", "msg", "rulesetname"))
.build();
RuleSet set1 = createRuleSetBuilder("ruleset1")
.addRuleSetByReference(set2, false)
.build();
assertEquals(2, set1.getRules().size(), "wrong rule size");
for (Rule rule : set1.getRules()) {
assertTrue(rule instanceof RuleReference, "not a rule reference");
RuleReference ruleReference = (RuleReference) rule;
assertEquals("foo", ruleReference.getRuleSetReference().getRuleSetFileName(), "wrong ruleset file name");
assertFalse(ruleReference.getRuleSetReference().isAllRules(), "should not be all rule reference");
}
}
@Test
void testApply0Rules() throws Exception {
RuleSet ruleset = createRuleSetBuilder("ruleset").build();
verifyRuleSet(ruleset, new HashSet<RuleViolation>());
}
@Test
void testEquals1() {
RuleSet s = createRuleSetBuilder("ruleset").build();
assertFalse(s.equals(null), "A ruleset cannot be equals to null");
}
@Test
@SuppressWarnings("PMD.UseAssertEqualsInsteadOfAssertTrue")
void testEquals2() {
RuleSet s = createRuleSetBuilder("ruleset").build();
assertTrue(s.equals(s), "A rulset must be equals to itself");
}
@Test
void testEquals3() {
RuleSet s = new RuleSetBuilder(new Random().nextLong())
.withName("basic rules")
.withDescription("desc")
.build();
assertFalse(s.equals("basic rules"), "A ruleset cannot be equals to another kind of object");
}
@Test
void testEquals4() {
RuleSet s1 = createRuleSetBuilder("my ruleset")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
RuleSet s2 = createRuleSetBuilder("my ruleset")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
assertEquals(s1, s2, "2 rulesets with same name and rules must be equals");
assertEquals(s1.hashCode(), s2.hashCode(), "Equals rulesets must have the same hashcode");
}
@Test
void testEquals5() {
RuleSet s1 = createRuleSetBuilder("my ruleset")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
RuleSet s2 = createRuleSetBuilder("my other ruleset")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
assertFalse(s1.equals(s2), "2 rulesets with different name but same rules must not be equals");
}
@Test
void testEquals6() {
RuleSet s1 = createRuleSetBuilder("my ruleset")
.addRule(new MockRule("name", "desc", "msg", "rulesetname"))
.build();
RuleSet s2 = createRuleSetBuilder("my ruleset")
.addRule(new MockRule("other rule", "desc", "msg", "rulesetname"))
.build();
assertFalse(s1.equals(s2), "2 rulesets with same name but different rules must not be equals");
}
@Test
void testLanguageApplies() {
Rule rule = new MockRule();
assertFalse(RuleSet.applies(rule, dummyLanguage2().getDefaultVersion()),
"Different languages should not apply");
assertTrue(RuleSet.applies(rule, dummyLanguage().getVersion("1.5")),
"Same language with no min/max should apply");
rule.setMinimumLanguageVersion(dummyLanguage().getVersion("1.5"));
assertTrue(RuleSet.applies(rule, dummyLanguage().getVersion("1.5")),
"Same language with valid min only should apply");
rule.setMaximumLanguageVersion(dummyLanguage().getVersion("1.6"));
assertTrue(RuleSet.applies(rule, dummyLanguage().getVersion("1.5")),
"Same language with valid min and max should apply");
assertFalse(RuleSet.applies(rule, dummyLanguage().getVersion("1.4")),
"Same language with outside range of min/max should not apply");
assertFalse(RuleSet.applies(rule, dummyLanguage().getVersion("1.7")),
"Same language with outside range of min/max should not apply");
}
@Test
void testAddExcludePattern() {
RuleSet ruleSet =
createRuleSetBuilder("ruleset1")
.withFileExclusions(Pattern.compile(".*"))
.build();
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(1, ruleSet.getFileExclusions().size(), "Invalid number of patterns");
}
@Test
void testExcludePatternAreOrdered() {
RuleSet ruleSet2 = createRuleSetBuilder("ruleset2")
.withFileExclusions(Pattern.compile(".*"))
.withFileExclusions(Pattern.compile(".*ha"))
.build();
assertEquals(Arrays.asList(".*", ".*ha"), toStrings(ruleSet2.getFileExclusions()), "Exclude pattern");
}
@Test
void testIncludePatternsAreOrdered() {
RuleSet ruleSet2 = createRuleSetBuilder("ruleset2")
.withFileInclusions(Pattern.compile(".*"))
.withFileInclusions(Arrays.asList(Pattern.compile(".*ha"), Pattern.compile(".*hb")))
.build();
assertEquals(Arrays.asList(".*", ".*ha", ".*hb"), toStrings(ruleSet2.getFileInclusions()), "Exclude pattern");
}
private List<String> toStrings(List<Pattern> strings) {
return strings.stream().map(Pattern::pattern).collect(Collectors.toList());
}
@Test
void testAddExcludePatterns() {
RuleSet ruleSet = createRuleSetBuilder("ruleset1")
.withFileExclusions(Pattern.compile(".*"))
.build();
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(1, ruleSet.getFileExclusions().size(), "Invalid number of patterns");
RuleSet ruleSet2 = createRuleSetBuilder("ruleset2")
.withFileExclusions(ruleSet.getFileExclusions())
.build();
assertNotNull(ruleSet2.getFileExclusions(), "Exclude patterns");
assertEquals(1, ruleSet2.getFileExclusions().size(), "Invalid number of patterns");
}
@Test
void testSetExcludePatterns() {
List<Pattern> excludePatterns = new ArrayList<>();
excludePatterns.add(Pattern.compile("ah*"));
excludePatterns.add(Pattern.compile(".*"));
RuleSet ruleSet = createRuleSetBuilder("ruleset").replaceFileExclusions(excludePatterns).build();
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(2, ruleSet.getFileExclusions().size(), "Invalid number of exclude patterns");
assertEquals("ah*", ruleSet.getFileExclusions().get(0).pattern(), "Exclude pattern");
assertEquals(".*", ruleSet.getFileExclusions().get(1).pattern(), "Exclude pattern");
assertNotNull(ruleSet.getFileInclusions(), "Include patterns");
assertEquals(0, ruleSet.getFileInclusions().size(), "Invalid number of include patterns");
}
@Test
void testAddIncludePattern() {
RuleSet ruleSet = createRuleSetBuilder("ruleset")
.withFileInclusions(Pattern.compile(".*"))
.build();
assertNotNull(ruleSet.getFileInclusions(), "Include patterns");
assertEquals(1, ruleSet.getFileInclusions().size(), "Invalid number of patterns");
assertEquals(".*", ruleSet.getFileInclusions().get(0).pattern(), "Include pattern");
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(0, ruleSet.getFileExclusions().size(), "Invalid number of exclude patterns");
}
@Test
void testAddIncludePatterns() {
RuleSet ruleSet = createRuleSetBuilder("ruleset1")
.withFileInclusions(Pattern.compile("ah*"), Pattern.compile(".*"))
.build();
RuleSet ruleSet2 = createRuleSetBuilder("ruleset1")
.withFileInclusions(ruleSet.getFileInclusions())
.build();
assertNotNull(ruleSet2.getFileInclusions(), "Include patterns");
assertEquals(2, ruleSet2.getFileInclusions().size(), "Invalid number of patterns");
assertEquals("ah*", ruleSet2.getFileInclusions().get(0).pattern(), "Include pattern");
assertEquals(".*", ruleSet2.getFileInclusions().get(1).pattern(), "Include pattern");
assertNotNull(ruleSet.getFileExclusions(), "Exclude patterns");
assertEquals(0, ruleSet.getFileExclusions().size(), "Invalid number of exclude patterns");
}
@Test
void testSetIncludePatterns() {
List<Pattern> includePatterns = new ArrayList<>();
includePatterns.add(Pattern.compile("ah*"));
includePatterns.add(Pattern.compile(".*"));
RuleSet ruleSet = createRuleSetBuilder("ruleset")
.replaceFileInclusions(includePatterns)
.build();
assertEquals(includePatterns, ruleSet.getFileInclusions(), "Include patterns");
assertNotNull(ruleSet.getFileInclusions(), "Exclude patterns");
assertEquals(0, ruleSet.getFileExclusions().size(), "Invalid number of exclude patterns");
}
@Test
void testIncludeExcludeApplies() {
TextFile file = TextFile.forPath(Paths.get("C:\\myworkspace\\project\\some\\random\\package\\RandomClass.java"), Charset.defaultCharset(), dummyVersion());
RuleSet ruleSet = createRuleSetBuilder("ruleset").build();
assertTrue(ruleSet.applies(file), "No patterns");
ruleSet = createRuleSetBuilder("ruleset")
.withFileExclusions(Pattern.compile("nomatch"))
.build();
assertTrue(ruleSet.applies(file), "Non-matching exclude");
ruleSet = createRuleSetBuilder("ruleset")
.withFileExclusions(Pattern.compile("nomatch"), Pattern.compile(".*/package/.*"))
.build();
assertFalse(ruleSet.applies(file), "Matching exclude");
ruleSet = createRuleSetBuilder("ruleset")
.withFileExclusions(Pattern.compile("nomatch"))
.withFileExclusions(Pattern.compile(".*/package/.*"))
.withFileInclusions(Pattern.compile(".*/randomX/.*"))
.build();
assertFalse(ruleSet.applies(file), "Non-matching include");
ruleSet = createRuleSetBuilder("ruleset")
.withFileExclusions(Pattern.compile("nomatch"))
.withFileExclusions(Pattern.compile(".*/package/.*"))
.withFileInclusions(Pattern.compile(".*/randomX/.*"))
.withFileInclusions(Pattern.compile(".*/random/.*"))
.build();
assertTrue(ruleSet.applies(file), "Matching include");
}
@Test
void testIncludeExcludeMultipleRuleSetWithRuleChainApplies() throws Exception {
Rule rule = new FooRule();
rule.setName("FooRule1");
rule.setLanguage(dummyLanguage());
RuleSet ruleSet1 = createRuleSetBuilder("RuleSet1").addRule(rule).build();
RuleSet ruleSet2 = createRuleSetBuilder("RuleSet2").addRule(rule).build();
RuleSets ruleSets = new RuleSets(listOf(ruleSet1, ruleSet2));
// Two violations
Report report = Report.buildReport(ctx1 -> ruleSets.apply(makeCompilationUnits(), ctx1));
assertEquals(2, report.getViolations().size(), "Violations");
// One violation
ruleSet1 = createRuleSetBuilder("RuleSet1")
.withFileExclusions(Pattern.compile(".*/package/.*"))
.addRule(rule)
.build();
RuleSets ruleSets2 = new RuleSets(listOf(ruleSet1, ruleSet2));
report = Report.buildReport(ctx -> ruleSets2.apply(makeCompilationUnits("C:\\package\\RandomClass.java"), ctx));
assertEquals(1, report.getViolations().size(), "Violations");
}
@Test
void copyConstructorDeepCopies() {
Rule rule = new FooRule();
rule.setName("FooRule1");
RuleSet ruleSet1 = createRuleSetBuilder("RuleSet1")
.addRule(rule)
.build();
RuleSet ruleSet2 = new RuleSet(ruleSet1);
assertEquals(ruleSet1, ruleSet2);
assertNotSame(ruleSet1, ruleSet2);
assertEquals(rule, ruleSet2.getRuleByName("FooRule1"));
assertNotSame(rule, ruleSet2.getRuleByName("FooRule1"));
}
private void verifyRuleSet(RuleSet ruleset, Set<RuleViolation> expected) throws Exception {
Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits());
assertEquals(expected.size(), report.getViolations().size(), "Invalid number of Violations Reported");
for (RuleViolation violation : report.getViolations()) {
assertTrue(expected.contains(violation), "Unexpected Violation Returned: " + violation);
}
for (RuleViolation violation : expected) {
assertTrue(report.getViolations().contains(violation), "Expected Violation not Returned: " + violation);
}
}
private RootNode makeCompilationUnits() {
return makeCompilationUnits("sampleFile.dummy");
}
private RootNode makeCompilationUnits(String filename) {
DummyRootNode node = helper.parse("dummyCode", filename);
node.setImage("Foo");
return node;
}
@Test
void ruleExceptionShouldBeReported() throws Exception {
RuleSet ruleset = createRuleSetBuilder("ruleExceptionShouldBeReported")
.addRule(new MockRule() {
@Override
public void apply(Node nodes, RuleContext ctx) {
throw new IllegalStateException("Test exception while applying rule");
}
})
.build();
Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits());
List<ProcessingError> errors = report.getProcessingErrors();
assertThat(errors, hasSize(1));
ProcessingError error = errors.get(0);
assertThat(error.getMsg(), containsString("java.lang.IllegalStateException: Test exception while applying rule\n"));
assertThat(error.getMsg(), containsString("Rule applied on node=dummyRootNode[@Image=Foo]"));
assertThat(error.getError().getCause(), instanceOf(IllegalStateException.class));
}
@Test
void ruleExceptionShouldNotStopProcessingFile() throws Exception {
RuleSet ruleset = createRuleSetBuilder("ruleExceptionShouldBeReported").addRule(new MockRule() {
@Override
public void apply(Node target, RuleContext ctx) {
throw new IllegalStateException("Test exception while applying rule");
}
}).addRule(new MockRule() {
@Override
public void apply(Node target, RuleContext ctx) {
addViolationWithMessage(ctx, target, "Test violation of the second rule in the ruleset");
}
}).build();
Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits("samplefile.dummy"));
List<ProcessingError> errors = report.getProcessingErrors();
assertThat(errors, hasSize(1));
ProcessingError error = errors.get(0);
assertThat(error.getMsg(), containsString("java.lang.IllegalStateException: Test exception while applying rule\n"));
assertThat(error.getMsg(), containsString("Rule applied on node=dummyRootNode[@Image=Foo]"));
assertThat(error.getError().getCause(), instanceOf(IllegalStateException.class));
assertThat(error.getFileId().getFileName(), equalTo("samplefile.dummy"));
assertThat(report.getViolations(), hasSize(1));
}
@Test
void ruleExceptionShouldNotStopProcessingFileWithRuleChain() throws Exception {
RuleSet ruleset = createRuleSetBuilder("ruleExceptionShouldBeReported").addRule(new MockRule() {
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forXPathNames(setOf("dummyRootNode"));
}
@Override
public void apply(Node target, RuleContext ctx) {
throw new UnsupportedOperationException("Test exception while applying rule");
}
}).addRule(new MockRule() {
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forXPathNames(setOf("dummyRootNode"));
}
@Override
public void apply(Node target, RuleContext ctx) {
addViolationWithMessage(ctx, target, "Test violation of the second rule in the ruleset");
}
}).build();
Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits());
List<ProcessingError> errors = report.getProcessingErrors();
assertThat(errors, hasSize(1));
ProcessingError error = errors.get(0);
assertThat(error.getMsg(), containsString("java.lang.UnsupportedOperationException: Test exception while applying rule\n"));
assertThat(error.getMsg(), containsString("Rule applied on node=dummyRootNode[@Image=Foo]"));
assertThat(error.getError().getCause(), instanceOf(UnsupportedOperationException.class));
assertThat(report.getViolations(), hasSize(1));
}
static class MockRule extends net.sourceforge.pmd.lang.rule.MockRule {
MockRule() {
super();
setLanguage(DummyLanguageModule.getInstance());
}
MockRule(String name, String description, String message, String ruleSetName, RulePriority priority) {
super(name, description, message, ruleSetName, priority);
setLanguage(DummyLanguageModule.getInstance());
}
MockRule(String name, String description, String message, String ruleSetName) {
super(name, description, message, ruleSetName);
setLanguage(DummyLanguageModule.getInstance());
}
}
}
| 24,664 | 40.314908 | 163 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RulesetFactoryTestBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.buildMap;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.text.MessageFormat;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.verification.VerificationMode;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.util.internal.xml.SchemaConstant;
import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
class RulesetFactoryTestBase {
protected MessageReporter mockReporter;
@BeforeEach
void setup() {
SimpleMessageReporter reporter = new SimpleMessageReporter(LoggerFactory.getLogger(RulesetFactoryTestBase.class));
mockReporter = spy(reporter);
}
protected void verifyNoWarnings() {
verifyNoMoreInteractions(mockReporter);
}
protected static Predicate<String> containing(String part) {
return new Predicate<String>() {
@Override
public boolean test(String it) {
String format = MessageFormat.format(it, new Object[0]);
return format.contains(part);
}
@Override
public String toString() {
return "string containing: " + part;
}
};
}
/**
* @param messageTest This is a MessageFormat string!
*/
protected void verifyFoundAWarningWithMessage(Predicate<String> messageTest) {
verifyFoundWarningWithMessage(times(1), messageTest);
}
/**
* @param messageTest This is a MessageFormat string!
*/
protected void verifyFoundWarningWithMessage(VerificationMode mode, Predicate<String> messageTest) {
verify(mockReporter, mode)
.logEx(eq(Level.WARN), argThat(messageTest::test), any(), any());
}
protected void verifyFoundAnErrorWithMessage(Predicate<String> messageTest) {
verify(mockReporter, times(1))
.logEx(eq(Level.ERROR), argThat(messageTest::test), any(), any());
}
protected RuleSet loadRuleSetInDir(String resourceDir, String ruleSetFilename) {
RuleSetLoader loader = new RuleSetLoader().withReporter(mockReporter);
return loader.loadFromResource(resourceDir + "/" + ruleSetFilename);
}
protected Rule loadFirstRule(String ruleSetXml) {
RuleSet rs = loadRuleSet(ruleSetXml);
return rs.getRules().iterator().next();
}
protected RuleSet loadRuleSet(String ruleSetXml) {
return loadRuleSet("dummyRuleset.xml", ruleSetXml);
}
protected RuleSet loadRuleSet(String fileName, String ruleSetXml) {
RuleSetLoader loader = new RuleSetLoader().withReporter(mockReporter);
return loader.loadFromString(fileName, ruleSetXml);
}
protected RuleSet loadRuleSetWithDeprecationWarnings(String ruleSetXml) {
PMDConfiguration config = new PMDConfiguration();
config.setReporter(mockReporter);
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
return pmd.newRuleSetLoader()
.warnDeprecated(true)
.enableCompatibility(false).loadFromString("dummyRuleset.xml", ruleSetXml);
}
}
protected void assertCannotParse(String xmlContent) {
assertThrows(RuleSetLoadException.class, () -> loadFirstRule(xmlContent));
}
/*
DSL to build a ruleset XML file with method calls.
*/
protected static @NonNull String rulesetXml(String... contents) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n"
+ "<ruleset name=\"Custom ruleset\" xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http:www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Ruleset which references a empty ruleset</description>\n" + "\n"
+ body(contents)
+ "</ruleset>\n";
}
protected static @NonNull String ruleRef(String ref) {
return "<rule ref=\"" + ref + "\"/>\n";
}
protected static @NonNull String rule(Map<SchemaConstant, String> attrs, String... body) {
return "<rule " + attrs(attrs) + ">\n"
+ body(body)
+ "</rule>";
}
protected static @NonNull String dummyRule(Consumer<Map<SchemaConstant, String>> attributes, String... body) {
return rule(buildMap(dummyRuleDefAttrs(), attributes), body);
}
protected static @NonNull String dummyRule(String... body) {
return dummyRule(m -> { }, body);
}
/**
* Default attributes used by {@link #dummyRule(Consumer, String...)}.
*/
protected static Map<SchemaConstant, String> dummyRuleDefAttrs() {
return buildMap(
map -> {
map.put(SchemaConstants.NAME, "MockRuleName");
map.put(SchemaConstants.LANGUAGE, DummyLanguageModule.TERSE_NAME);
map.put(SchemaConstants.CLASS, net.sourceforge.pmd.lang.rule.MockRule.class.getName());
map.put(SchemaConstants.MESSAGE, "avoid the mock rule");
}
);
}
private static @NonNull String attrs(Map<SchemaConstant, String> str) {
return str.entrySet().stream()
.map(it -> it.getKey().xmlName() + "=\"" + it.getValue() + "\"")
.collect(Collectors.joining(" "));
}
protected static @NonNull String rulesetRef(String ref, String... body) {
return ruleRef(ref, body);
}
protected static @NonNull String ruleRef(String ref, String... body) {
return "<rule ref=\"" + ref + "\">\n"
+ body(body)
+ "</rule>\n";
}
protected static @NonNull String excludePattern(String pattern) {
return tagOneLine("exclude-pattern", pattern);
}
protected static @NonNull String excludeRule(String name) {
return emptyTag("exclude", buildMap(map -> map.put(SchemaConstants.NAME, name)));
}
protected static @NonNull String includePattern(String pattern) {
return tagOneLine("include-pattern", pattern);
}
protected static @NonNull String priority(String prio) {
return tagOneLine("priority", prio);
}
protected static @NonNull String description(String description) {
return tagOneLine("description", description);
}
protected static @NonNull String body(String... lines) {
return String.join("\n", lines);
}
protected static @NonNull String properties(String... body) {
return tag("properties", body);
}
protected static @NonNull String propertyWithValueAttr(String name, String valueAttr) {
return "<property name='" + name + "' value='" + valueAttr + "/>\n";
}
protected static @NonNull String propertyDefWithValueAttr(String name,
String description,
String type,
String valueAttr) {
return emptyTag("property", buildMap(
map -> {
map.put(SchemaConstants.NAME, name);
map.put(SchemaConstants.DESCRIPTION, description);
map.put(SchemaConstants.PROPERTY_TYPE, type);
map.put(SchemaConstants.PROPERTY_VALUE, valueAttr);
}
));
}
private static @NonNull String tag(String tagName, String... body) {
return "<" + tagName + ">\n"
+ body(body)
+ "</" + tagName + ">";
}
private static @NonNull String emptyTag(String tagName, Map<SchemaConstant, String> attrs) {
return "<" + tagName + " " + attrs(attrs) + " />";
}
private static @NonNull String tagOneLine(String tagName, String text) {
return "<" + tagName + ">" + text + "</" + tagName + ">";
}
}
| 8,767 | 35.231405 | 131 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetWriterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSet.RuleSetBuilder;
import net.sourceforge.pmd.lang.rule.RuleReference;
/**
* Unit test for {@link RuleSetWriter}.
*
*/
class RuleSetWriterTest {
private ByteArrayOutputStream out;
private RuleSetWriter writer;
/**
* Prepare the output stream.
*/
@BeforeEach
void setupOutputStream() {
out = new ByteArrayOutputStream();
writer = new RuleSetWriter(out);
}
/**
* Closes the output stream at the end.
*/
@AfterEach
void cleanupStream() {
if (writer != null) {
writer.close();
}
}
/**
* Tests the exclude rule behavior. See bug #945.
*
* @throws Exception
* any error
*/
@Test
void testWrite() throws Exception {
RuleSet braces = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/TestRuleset1.xml");
RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong())
.withName("ruleset")
.withDescription("ruleset description")
.addRuleSetByReference(braces, true, "MockRule2")
.build();
writer.write(ruleSet);
String written = out.toString("UTF-8");
assertTrue(written.contains("<exclude name=\"MockRule2\""));
}
/**
* Unit test for #1312 see https://sourceforge.net/p/pmd/bugs/1312/
*
* @throws Exception
* any error
*/
@Test
void testRuleReferenceOverriddenName() throws Exception {
RuleSet rs = new RuleSetLoader().loadFromResource("rulesets/dummy/basic.xml");
RuleReference ruleRef = new RuleReference(
rs.getRuleByName("DummyBasicMockRule"),
new RuleSetReference("rulesets/dummy/basic.xml"));
ruleRef.setName("Foo"); // override the name
RuleSet ruleSet = RuleSet.forSingleRule(ruleRef);
writer.write(ruleSet);
String written = out.toString("UTF-8");
assertTrue(written.contains("ref=\"rulesets/dummy/basic.xml/DummyBasicMockRule\""));
}
}
| 2,454 | 25.978022 | 102 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleReferenceTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyLanguage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
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.Dummy2LanguageModule;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
class RuleReferenceTest {
@Test
void testRuleSetReference() {
RuleSetReference ruleSetReference = new RuleSetReference("somename");
RuleReference ruleReference = new RuleReference(null, ruleSetReference);
assertEquals(ruleSetReference, ruleReference.getRuleSetReference(), "Not same rule set reference");
}
@Test
void testOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
Language dummyLang = dummyLanguage();
rule.setLanguage(dummyLang);
rule.setName("name1");
rule.setProperty(PROPERTY1_DESCRIPTOR, "value1");
rule.setMessage("message1");
rule.setDescription("description1");
rule.addExample("example1");
rule.setExternalInfoUrl("externalInfoUrl1");
rule.setPriority(RulePriority.HIGH);
final PropertyDescriptor<String> PROPERTY2_DESCRIPTOR = PropertyFactory.stringProperty("property2").desc("Test property").defaultValue("").build();
RuleReference ruleReference = new RuleReference(rule, null);
ruleReference.definePropertyDescriptor(PROPERTY2_DESCRIPTOR);
ruleReference.setMinimumLanguageVersion(dummyLang.getVersion("1.3"));
ruleReference.setMaximumLanguageVersion(dummyLang.getVersion("1.7"));
ruleReference.setDeprecated(true);
ruleReference.setName("name2");
ruleReference.setProperty(PROPERTY1_DESCRIPTOR, "value2");
ruleReference.setProperty(PROPERTY2_DESCRIPTOR, "value3");
ruleReference.setMessage("message2");
ruleReference.setDescription("description2");
ruleReference.addExample("example2");
ruleReference.setExternalInfoUrl("externalInfoUrl2");
ruleReference.setPriority(RulePriority.MEDIUM_HIGH);
validateOverriddenValues(PROPERTY1_DESCRIPTOR, PROPERTY2_DESCRIPTOR, ruleReference);
}
@Test
void testLanguageOverrideDisallowed() {
MockRule rule = new MockRule();
Language dummyLang = dummyLanguage();
rule.setLanguage(dummyLang);
RuleReference ruleReference = new RuleReference(rule, null);
assertThrows(UnsupportedOperationException.class, () -> ruleReference.setLanguage(Dummy2LanguageModule.getInstance()));
assertEquals(dummyLang, ruleReference.getLanguage());
assertThrows(IllegalArgumentException.class, () -> ruleReference.setMaximumLanguageVersion(Dummy2LanguageModule.getInstance().getVersion("1.0")));
assertEquals(rule.getMaximumLanguageVersion(), ruleReference.getOverriddenMaximumLanguageVersion());
assertThrows(IllegalArgumentException.class, () -> ruleReference.setMinimumLanguageVersion(Dummy2LanguageModule.getInstance().getVersion("1.0")));
assertEquals(rule.getMinimumLanguageVersion(), ruleReference.getMinimumLanguageVersion());
}
@Test
void testDeepCopyOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
Language dummyLang = dummyLanguage();
rule.setLanguage(dummyLang);
rule.setName("name1");
rule.setProperty(PROPERTY1_DESCRIPTOR, "value1");
rule.setMessage("message1");
rule.setDescription("description1");
rule.addExample("example1");
rule.setExternalInfoUrl("externalInfoUrl1");
rule.setPriority(RulePriority.HIGH);
final PropertyDescriptor<String> PROPERTY2_DESCRIPTOR = PropertyFactory.stringProperty("property2").desc("Test property").defaultValue("").build();
RuleReference ruleReference = new RuleReference(rule, null);
ruleReference.definePropertyDescriptor(PROPERTY2_DESCRIPTOR);
ruleReference.setLanguage(dummyLang);
ruleReference.setMinimumLanguageVersion(dummyLang.getVersion("1.3"));
ruleReference.setMaximumLanguageVersion(dummyLang.getVersion("1.7"));
ruleReference.setDeprecated(true);
ruleReference.setName("name2");
ruleReference.setProperty(PROPERTY1_DESCRIPTOR, "value2");
ruleReference.setProperty(PROPERTY2_DESCRIPTOR, "value3");
ruleReference.setMessage("message2");
ruleReference.setDescription("description2");
ruleReference.addExample("example2");
ruleReference.setExternalInfoUrl("externalInfoUrl2");
ruleReference.setPriority(RulePriority.MEDIUM_HIGH);
validateOverriddenValues(PROPERTY1_DESCRIPTOR, PROPERTY2_DESCRIPTOR, (RuleReference) ruleReference.deepCopy());
}
private void validateOverriddenValues(final PropertyDescriptor<String> propertyDescriptor1,
final PropertyDescriptor<String> propertyDescriptor2, RuleReference ruleReference) {
assertEquals(dummyLanguage(), ruleReference.getLanguage(),
"Override failed");
assertEquals(dummyLanguage().getVersion("1.3"), ruleReference.getMinimumLanguageVersion(),
"Override failed");
assertEquals(dummyLanguage().getVersion("1.3"), ruleReference.getOverriddenMinimumLanguageVersion(),
"Override failed");
assertEquals(dummyLanguage().getVersion("1.7"), ruleReference.getMaximumLanguageVersion(),
"Override failed");
assertEquals(dummyLanguage().getVersion("1.7"), ruleReference.getOverriddenMaximumLanguageVersion(),
"Override failed");
assertEquals(false, ruleReference.getRule().isDeprecated(), "Override failed");
assertEquals(true, ruleReference.isDeprecated(), "Override failed");
assertEquals(true, ruleReference.isOverriddenDeprecated(), "Override failed");
assertEquals("name2", ruleReference.getName(), "Override failed");
assertEquals("name2", ruleReference.getOverriddenName(), "Override failed");
assertEquals("value2", ruleReference.getProperty(propertyDescriptor1), "Override failed");
assertEquals("value3", ruleReference.getProperty(propertyDescriptor2), "Override failed");
assertTrue(ruleReference.getPropertyDescriptors().contains(propertyDescriptor1), "Override failed");
assertTrue(ruleReference.getPropertyDescriptors().contains(propertyDescriptor2), "Override failed");
assertFalse(ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor1), "Override failed");
assertTrue(ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor2), "Override failed");
assertTrue(ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1),
"Override failed");
assertTrue(ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2),
"Override failed");
assertTrue(ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1),
"Override failed");
assertTrue(ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2),
"Override failed");
assertEquals("message2", ruleReference.getMessage(), "Override failed");
assertEquals("message2", ruleReference.getOverriddenMessage(), "Override failed");
assertEquals("description2", ruleReference.getDescription(), "Override failed");
assertEquals("description2", ruleReference.getOverriddenDescription(), "Override failed");
assertEquals(2, ruleReference.getExamples().size(), "Override failed");
assertEquals("example1", ruleReference.getExamples().get(0), "Override failed");
assertEquals("example2", ruleReference.getExamples().get(1), "Override failed");
assertEquals("example2", ruleReference.getOverriddenExamples().get(0), "Override failed");
assertEquals("externalInfoUrl2", ruleReference.getExternalInfoUrl(), "Override failed");
assertEquals("externalInfoUrl2", ruleReference.getOverriddenExternalInfoUrl(), "Override failed");
assertEquals(RulePriority.MEDIUM_HIGH, ruleReference.getPriority(), "Override failed");
assertEquals(RulePriority.MEDIUM_HIGH, ruleReference.getOverriddenPriority(), "Override failed");
}
@Test
void testNotOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
rule.setLanguage(dummyLanguage());
rule.setMinimumLanguageVersion(dummyLanguage().getVersion("1.3"));
rule.setMaximumLanguageVersion(dummyLanguage().getVersion("1.7"));
rule.setName("name1");
rule.setProperty(PROPERTY1_DESCRIPTOR, "value1");
rule.setMessage("message1");
rule.setDescription("description1");
rule.addExample("example1");
rule.setExternalInfoUrl("externalInfoUrl1");
rule.setPriority(RulePriority.HIGH);
RuleReference ruleReference = new RuleReference(rule, null);
ruleReference
.setMinimumLanguageVersion(dummyLanguage().getVersion("1.3"));
ruleReference
.setMaximumLanguageVersion(dummyLanguage().getVersion("1.7"));
ruleReference.setDeprecated(false);
ruleReference.setName("name1");
ruleReference.setProperty(PROPERTY1_DESCRIPTOR, "value1");
ruleReference.setMessage("message1");
ruleReference.setDescription("description1");
ruleReference.addExample("example1");
ruleReference.setExternalInfoUrl("externalInfoUrl1");
ruleReference.setPriority(RulePriority.HIGH);
assertEquals(dummyLanguage().getVersion("1.3"), ruleReference.getMinimumLanguageVersion(),
"Override failed");
assertNull(ruleReference.getOverriddenMinimumLanguageVersion(), "Override failed");
assertEquals(dummyLanguage().getVersion("1.7"), ruleReference.getMaximumLanguageVersion(),
"Override failed");
assertNull(ruleReference.getOverriddenMaximumLanguageVersion(), "Override failed");
assertEquals(false, ruleReference.isDeprecated(), "Override failed");
assertNull(ruleReference.isOverriddenDeprecated(), "Override failed");
assertEquals("name1", ruleReference.getName(), "Override failed");
assertNull(ruleReference.getOverriddenName(), "Override failed");
assertEquals("value1", ruleReference.getProperty(PROPERTY1_DESCRIPTOR), "Override failed");
assertEquals("message1", ruleReference.getMessage(), "Override failed");
assertNull(ruleReference.getOverriddenMessage(), "Override failed");
assertEquals("description1", ruleReference.getDescription(), "Override failed");
assertNull(ruleReference.getOverriddenDescription(), "Override failed");
assertEquals(1, ruleReference.getExamples().size(), "Override failed");
assertEquals("example1", ruleReference.getExamples().get(0), "Override failed");
assertNull(ruleReference.getOverriddenExamples(), "Override failed");
assertEquals("externalInfoUrl1", ruleReference.getExternalInfoUrl(), "Override failed");
assertNull(ruleReference.getOverriddenExternalInfoUrl(), "Override failed");
assertEquals(RulePriority.HIGH, ruleReference.getPriority(), "Override failed");
assertNull(ruleReference.getOverriddenPriority(), "Override failed");
}
}
| 12,611 | 52.897436 | 155 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryMessagesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import org.junit.jupiter.api.Test;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class RuleSetFactoryMessagesTest extends RulesetFactoryTestBase {
@Test
void testFullMessage() throws Exception {
String log = SystemLambda.tapSystemErr(() -> assertCannotParse(
rulesetXml(
dummyRule(
priority("not a priority")
)
)
));
assertThat(log, containsString(
"Error at dummyRuleset.xml:9:1\n"
+ " 7| \n"
+ " 8| <rule name=\"MockRuleName\" language=\"dummy\" class=\"net.sourceforge.pmd.lang.rule.MockRule\" message=\"avoid the mock rule\">\n"
+ " 9| <priority>not a priority</priority></rule></ruleset>\n"
+ " ^^^^^^^^^ Not a valid priority: 'not a priority', expected a number in [1,5]"
));
}
}
| 1,126 | 31.2 | 154 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.ReportTest.violation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Comparator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextRange2d;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
class RuleViolationTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
private FileId filename = FileId.fromPathLikeString("filename");
@Test
void testConstructor1() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
DummyRootNode s = helper.parse("abcd", filename);
RuleViolation r = new ParametricRuleViolation(rule, s, rule.getMessage());
assertEquals(rule, r.getRule(), "object mismatch");
assertEquals(1, r.getBeginLine(), "line number is wrong");
assertSame(filename, r.getFileId(), "filename is wrong");
}
@Test
void testConstructor2() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
DummyRootNode s = helper.parse("abcd", filename);
RuleViolation r = new ParametricRuleViolation(rule, s, "description");
assertEquals(rule, r.getRule(), "object mismatch");
assertEquals(1, r.getBeginLine(), "line number is wrong");
assertSame(filename, r.getFileId(), "filename is wrong");
assertEquals("description", r.getDescription(), "description is wrong");
}
@Test
void testComparatorWithDifferentFilenames() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
DummyNode s = helper.parse("(abc)", FileId.fromPathLikeString("f1")).getFirstChild();
DummyNode s1 = helper.parse("(abc)", FileId.fromPathLikeString("f2")).getFirstChild();
RuleViolation r1 = new ParametricRuleViolation(rule, s, "description");
RuleViolation r2 = new ParametricRuleViolation(rule, s1, "description");
assertEquals(-1, comp.compare(r1, r2));
assertEquals(1, comp.compare(r2, r1));
}
@Test
void testComparatorWithSameFileDifferentLines() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
DummyRootNode root = helper.parse("(abc) (def)");
DummyNode abcChild = root.getChild(0);
DummyNode defChild = root.getChild(1);
RuleViolation r1 = new ParametricRuleViolation(rule, abcChild, "description");
RuleViolation r2 = new ParametricRuleViolation(rule, defChild, "description");
assertTrue(comp.compare(r1, r2) < 0);
assertTrue(comp.compare(r2, r1) > 0);
}
@Test
void testComparatorWithSameFileSameLines() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
FileLocation loc = FileLocation.range(filename, TextRange2d.range2d(10, 1, 15, 10));
RuleViolation r1 = violation(rule, loc, "description");
RuleViolation r2 = violation(rule, loc, "description");
assertEquals(0, comp.compare(r1, r2));
assertEquals(0, comp.compare(r2, r1));
}
}
| 3,857 | 41.395604 | 94 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/FileSelectorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageFilenameFilter;
/**
* Tests on FileSelector.
*
* @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be
*/
class FileSelectorTest {
/**
* Test wanted selection of a source file.
*/
@Test
void testWantedFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(DummyLanguageModule.getInstance());
File javaFile = new File("/path/to/myFile.dummy");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertTrue(selected, "This file should be selected !");
}
/**
* Test unwanted selection of a non source file.
*/
@Test
void testUnwantedFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(DummyLanguageModule.getInstance());
File javaFile = new File("/path/to/myFile.txt");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertFalse(selected, "Not-source file must not be selected!");
}
/**
* Test unwanted selection of a java file.
*/
@Test
void testUnwantedJavaFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(DummyLanguageModule.getInstance());
File javaFile = new File("/path/to/MyClass.java");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertFalse(selected, "Unwanted java file must not be selected!");
}
}
| 1,884 | 28.920635 | 108 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleContextTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.ReportTestUtil.getReport;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil;
class RuleContextTest {
@Test
void testMessage() throws Exception {
Report report = getReport(new FooRule(), (r, ctx) -> ctx.addViolationWithMessage(DummyTreeUtil.tree(DummyTreeUtil::root), "message with \"'{'\""));
assertEquals("message with \"{\"", report.getViolations().get(0).getDescription());
}
@Test
void testMessageEscaping() throws Exception {
RuleViolation violation = makeViolation("message with \"'{'\"");
assertEquals("message with \"{\"", violation.getDescription());
}
@Test
void testMessageEscaping2() throws Exception {
RuleViolation violation = makeViolation("message with ${ohio}");
assertEquals("message with ${ohio}", violation.getDescription());
}
private RuleViolation makeViolation(String unescapedMessage, Object... args) throws Exception {
Report report = getReport(new FooRule(), (r, ctx) -> {
DummyRootNode node = DummyTreeUtil.tree(DummyTreeUtil::root);
ctx.addViolationWithMessage(node, unescapedMessage, args);
});
return report.getViolations().get(0);
}
}
| 1,533 | 30.958333 | 155 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.StringWriter;
import java.util.function.Consumer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
class ReportTest {
// Files are grouped together now.
@Test
void testSortedReportFile() {
Renderer rend = new XMLRenderer();
String result = render(rend, r -> {
FileLocation s = getNode(10, 5, "foo");
Rule rule1 = new MockRule("name", "desc", "msg", "rulesetname");
r.onRuleViolation(violation(rule1, s));
FileLocation s1 = getNode(10, 5, "bar");
Rule rule2 = new MockRule("name", "desc", "msg", "rulesetname");
r.onRuleViolation(violation(rule2, s1));
});
assertThat(result, containsString("bar"));
assertThat(result, containsString("foo"));
assertTrue(result.indexOf("bar") < result.indexOf("foo"), "sort order wrong");
}
@Test
void testSortedReportLine() {
Renderer rend = new XMLRenderer();
String result = render(rend, r -> {
FileLocation node1 = getNode(20, 5, "foo1"); // line 20: after rule2 violation
Rule rule1 = new MockRule("rule1", "rule1", "msg", "rulesetname");
r.onRuleViolation(violation(rule1, node1));
FileLocation node2 = getNode(10, 5, "foo1"); // line 10: before rule1 violation
Rule rule2 = new MockRule("rule2", "rule2", "msg", "rulesetname");
r.onRuleViolation(violation(rule2, node2)); // same file!!
});
assertTrue(result.indexOf("rule2") < result.indexOf("rule1"), "sort order wrong");
}
@Test
void testIterator() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
FileLocation loc1 = getNode(5, 5, "file1");
FileLocation loc2 = getNode(5, 6, "file1");
Report r = Report.buildReport(it -> {
it.onRuleViolation(violation(rule, loc1));
it.onRuleViolation(violation(rule, loc2));
});
assertEquals(2, r.getViolations().size());
}
@Test
void testFilterViolations() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
FileLocation loc1 = getNode(5, 5, "file1");
FileLocation loc2 = getNode(5, 6, "file1");
Report r = Report.buildReport(it -> {
it.onRuleViolation(violation(rule, loc1));
it.onRuleViolation(violation(rule, loc2, "to be filtered"));
});
Report filtered = r.filterViolations(ruleViolation -> !"to be filtered".equals(ruleViolation.getDescription()));
assertEquals(1, filtered.getViolations().size());
assertEquals("msg", filtered.getViolations().get(0).getDescription());
}
@Test
void testUnion() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
FileLocation loc1 = getNode(1, 2, "file1");
Report report1 = Report.buildReport(it -> it.onRuleViolation(violation(rule, loc1)));
FileLocation loc2 = getNode(2, 1, "file1");
Report report2 = Report.buildReport(it -> it.onRuleViolation(violation(rule, loc2)));
Report union = report1.union(report2);
assertEquals(2, union.getViolations().size());
}
public static @NonNull RuleViolation violation(Rule rule, FileLocation loc2) {
return violation(rule, loc2, rule.getMessage());
}
public static @NonNull RuleViolation violation(Rule rule, FileLocation loc1, String rule1) {
return new ParametricRuleViolation(rule, loc1, rule1);
}
private static FileLocation getNode(int line, int column, String filename) {
return FileLocation.caret(FileId.fromPathLikeString(filename), line, column);
}
public static String render(Renderer renderer, Consumer<? super FileAnalysisListener> listenerEffects) {
return renderGlobal(renderer, globalListener -> {
LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
TextFile dummyFile = TextFile.forCharSeq("dummyText", FileId.fromPathLikeString("file"), dummyVersion);
try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) {
listenerEffects.accept(fal);
} catch (Exception e) {
throw new AssertionError(e);
}
});
}
public static String renderGlobal(Renderer renderer, Consumer<? super GlobalAnalysisListener> listenerEffects) {
StringWriter writer = new StringWriter();
renderer.setWriter(writer);
try (GlobalAnalysisListener listener = renderer.newListener()) {
listenerEffects.accept(listener);
} catch (Exception e) {
throw new AssertionError(e);
}
return writer.toString();
}
}
| 5,756 | 38.431507 | 120 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.Collections;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.SemanticErrorReporter;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* @author Clément Fournier
*/
public class DummyParsingHelper implements Extension, BeforeEachCallback, AfterEachCallback {
private LanguageProcessor dummyProcessor;
public DummyParsingHelper() {
}
public DummyRootNode parse(String code) {
return parse(code, FileId.UNKNOWN);
}
public DummyRootNode parse(String code, String filename) {
return parse(code, FileId.fromPathLikeString(filename));
}
public DummyRootNode parse(String code, FileId filename) {
LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion();
ParserTask task = new ParserTask(
TextDocument.readOnlyString(code, filename, version),
SemanticErrorReporter.noop(),
LanguageProcessorRegistry.singleton(dummyProcessor));
return (DummyRootNode) dummyProcessor.services().getParser().parse(task);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
dummyProcessor.close();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
LanguageProcessorRegistry registry = LanguageProcessorRegistry.create(
LanguageRegistry.PMD,
Collections.emptyMap(),
MessageReporter.quiet()
);
dummyProcessor = registry.getProcessor(DummyLanguageModule.getInstance());
}
}
| 2,375 | 33.434783 | 93 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/PmdCoreTestUtils.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import net.sourceforge.pmd.lang.Dummy2LanguageModule;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
/**
* Helper methods.
*/
public final class PmdCoreTestUtils {
private PmdCoreTestUtils() {
}
public static DummyLanguageModule dummyLanguage() {
return DummyLanguageModule.getInstance();
}
public static Dummy2LanguageModule dummyLanguage2() {
return Dummy2LanguageModule.getInstance();
}
public static <T extends Rule> T setDummyLanguage(T rule) {
rule.setLanguage(dummyLanguage());
return rule;
}
public static LanguageVersion dummyVersion() {
return dummyLanguage().getDefaultVersion();
}
}
| 857 | 22.189189 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/ReportTestUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.function.BiConsumer;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.document.TestMessageReporter;
public final class ReportTestUtil {
private ReportTestUtil() {
// utility
}
public static Report getReport(Rule rule, BiConsumer<Rule, RuleContext> sideEffects) {
return Report.buildReport(listener -> sideEffects.accept(rule, RuleContext.create(listener, rule)));
}
public static Report getReportForRuleApply(Rule rule, Node node) {
return getReport(rule, (r, ctx) -> {
r.initialize(node.getAstInfo().getLanguageProcessor());
r.apply(node, ctx);
});
}
public static Report getReportForRuleSetApply(RuleSet ruleset, RootNode node) {
return Report.buildReport(listener -> {
RuleSets ruleSets = new RuleSets(ruleset);
LanguageProcessorRegistry registry = LanguageProcessorRegistry.singleton(node.getAstInfo().getLanguageProcessor());
ruleSets.initializeRules(registry, new TestMessageReporter());
ruleSets.apply(node, listener);
});
}
}
| 1,357 | 32.95 | 127 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleWithProperties.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import java.util.List;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* Sample rule that detect any node with an image of "Foo", similar to
* {@link FooRule}. It additionally has some properties in order to test the
* renderers. Used for testing.
*/
public class RuleWithProperties extends FooRule {
public static final PropertyDescriptor<String> STRING_PROPERTY_DESCRIPTOR =
PropertyFactory.stringProperty("stringProperty")
.desc("simple string property")
.defaultValue("")
.build();
public static final PropertyDescriptor<List<String>> MULTI_STRING_PROPERTY_DESCRIPTOR =
PropertyFactory.stringListProperty("multiString")
.desc("multi string property")
.defaultValues("default1", "default2")
.delim(',')
.build();
public RuleWithProperties() {
definePropertyDescriptor(STRING_PROPERTY_DESCRIPTOR);
definePropertyDescriptor(MULTI_STRING_PROPERTY_DESCRIPTOR);
}
}
| 1,270 | 33.351351 | 91 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryCompatibilityTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class RuleSetFactoryCompatibilityTest {
@Test
void testCorrectOldReference() throws Exception {
final String ruleset = "<?xml version=\"1.0\"?>\n" + "\n" + "<ruleset name=\"Test\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Test</description>\n" + "\n"
+ " <rule ref=\"rulesets/dummy/notexisting.xml/DummyBasicMockRule\" />\n" + "</ruleset>\n";
RuleSetFactoryCompatibility compat = new RuleSetFactoryCompatibility();
compat.addFilterRuleMoved("dummy", "notexisting", "basic", "DummyBasicMockRule");
RuleSetLoader rulesetLoader = new RuleSetLoader().setCompatibility(compat);
RuleSet createdRuleSet = rulesetLoader.loadFromString("dummy.xml", ruleset);
assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
}
@Test
void testCorrectMovedAndRename() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMoved("dummy", "notexisting", "basic", "OldDummyBasicMockRule");
rsfc.addFilterRuleRenamed("dummy", "basic", "OldDummyBasicMockRule", "NewNameForDummyBasicMockRule");
String out = rsfc.applyRef("rulesets/dummy/notexisting.xml/OldDummyBasicMockRule");
assertEquals("rulesets/dummy/basic.xml/NewNameForDummyBasicMockRule", out);
}
@Test
void testExclusion() {
final String ruleset = "<?xml version=\"1.0\"?>\n" + "\n" + "<ruleset name=\"Test\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd\">\n"
+ " <description>Test</description>\n" + "\n" + " <rule ref=\"rulesets/dummy/basic.xml\">\n"
+ " <exclude name=\"OldNameOfSampleXPathRule\"/>\n" + " </rule>\n" + "</ruleset>\n";
RuleSetFactoryCompatibility compat = new RuleSetFactoryCompatibility();
compat.addFilterRuleRenamed("dummy", "basic", "OldNameOfSampleXPathRule", "SampleXPathRule");
RuleSetLoader rulesetLoader = new RuleSetLoader().setCompatibility(compat);
RuleSet createdRuleSet = rulesetLoader.loadFromString("dummy.xml", ruleset);
assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
assertNull(createdRuleSet.getRuleByName("SampleXPathRule"));
}
@Test
void testExclusionRenamedAndMoved() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMovedAndRenamed("dummy", "oldbasic", "OldDummyBasicMockRule", "basic", "NewNameForDummyBasicMockRule");
String in = "rulesets/dummy/oldbasic.xml";
String out = rsfc.applyRef(in);
assertEquals(in, out);
}
@Test
void testFilter() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMoved("dummy", "notexisting", "basic", "DummyBasicMockRule");
rsfc.addFilterRuleRemoved("dummy", "basic", "DeletedRule");
rsfc.addFilterRuleRenamed("dummy", "basic", "OldNameOfBasicMockRule", "NewNameOfBasicMockRule");
assertEquals("rulesets/dummy/basic.xml/DummyBasicMockRule",
rsfc.applyRef("rulesets/dummy/notexisting.xml/DummyBasicMockRule"));
assertEquals("rulesets/dummy/basic.xml/NewNameOfBasicMockRule",
rsfc.applyRef("rulesets/dummy/basic.xml/OldNameOfBasicMockRule"));
assertNull(rsfc.applyRef("rulesets/dummy/basic.xml/DeletedRule"));
}
@Test
void testExclusionFilter() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleRenamed("dummy", "basic", "AnotherOldNameOfBasicMockRule", "NewNameOfBasicMockRule");
String out = rsfc.applyExclude("rulesets/dummy/basic.xml", "AnotherOldNameOfBasicMockRule", false);
assertEquals("NewNameOfBasicMockRule", out);
}
}
| 4,674 | 43.951923 | 135 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.ReportTestUtil.getReportForRuleApply;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
class AbstractRuleTest {
private static class MyRule extends AbstractRule {
private static final PropertyDescriptor<String> FOO_PROPERTY = PropertyFactory.stringProperty("foo").desc("foo property").defaultValue("x").build();
private static final PropertyDescriptor<String> FOO_DEFAULT_PROPERTY = PropertyFactory.stringProperty("fooDefault")
.defaultValue("bar")
.desc("Property without value uses default value")
.build();
private static final PropertyDescriptor<String> XPATH_PROPERTY = PropertyFactory.stringProperty("xpath").desc("xpath property").defaultValue("").build();
MyRule() {
definePropertyDescriptor(FOO_PROPERTY);
definePropertyDescriptor(XPATH_PROPERTY);
definePropertyDescriptor(FOO_DEFAULT_PROPERTY);
setName("MyRule");
setMessage("my rule msg");
setPriority(RulePriority.MEDIUM);
setProperty(FOO_PROPERTY, "value");
}
@Override
public void apply(Node target, RuleContext ctx) {
}
}
private static class MyOtherRule extends AbstractRule {
private static final PropertyDescriptor<String> FOO_PROPERTY = PropertyFactory.stringProperty("foo").desc("foo property").defaultValue("x").build();
MyOtherRule() {
definePropertyDescriptor(FOO_PROPERTY);
setName("MyOtherRule");
setMessage("my other rule");
setPriority(RulePriority.MEDIUM);
setProperty(FOO_PROPERTY, "value");
}
@Override
public void apply(Node target, RuleContext ctx) {
}
}
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@Test
void testCreateRV() {
MyRule r = new MyRule();
r.setRuleSetName("foo");
DummyRootNode s = helper.parse("abc()", FileId.fromPathLikeString("abc"));
RuleViolation rv = new ParametricRuleViolation(r, s, r.getMessage());
assertEquals(1, rv.getBeginLine(), "Line number mismatch!");
assertEquals("abc", rv.getFileId().getOriginalPath(), "Filename mismatch!");
assertEquals(r, rv.getRule(), "Rule object mismatch!");
assertEquals("my rule msg", rv.getDescription(), "Rule msg mismatch!");
assertEquals("foo", rv.getRule().getRuleSetName(), "RuleSet name mismatch!");
}
@Test
void testCreateRV2() {
MyRule r = new MyRule();
DummyRootNode s = helper.parse("abc()", FileId.fromPathLikeString("filename"));
RuleViolation rv = new ParametricRuleViolation(r, s, "specificdescription");
assertEquals(1, rv.getBeginLine(), "Line number mismatch!");
assertEquals("filename", rv.getFileId().getOriginalPath(), "Filename mismatch!");
assertEquals(r, rv.getRule(), "Rule object mismatch!");
assertEquals("specificdescription", rv.getDescription(), "Rule description mismatch!");
}
@Test
void testRuleWithVariableInMessage() {
MyRule r = new MyRule() {
@Override
public void apply(Node target, RuleContext ctx) {
ctx.addViolation(target);
}
};
r.definePropertyDescriptor(PropertyFactory.intProperty("testInt").desc("description").require(inRange(0, 100)).defaultValue(10).build());
r.setMessage("Message ${packageName} ${className} ${methodName} ${variableName} ${testInt} ${noSuchProperty}");
DummyRootNode s = helper.parse("abc()", FileId.UNKNOWN);
RuleViolation rv = getReportForRuleApply(r, s).getViolations().get(0);
assertEquals("Message foo ${className} ${methodName} ${variableName} 10 ${noSuchProperty}", rv.getDescription());
}
@Test
void testRuleSuppress() {
DummyRootNode n = helper.parse("abc()", FileId.UNKNOWN)
.withNoPmdComments(Collections.singletonMap(1, "ohio"));
FileAnalysisListener listener = mock(FileAnalysisListener.class);
RuleContext ctx = RuleContext.create(listener, new MyRule());
ctx.addViolationWithMessage(n, "message");
verify(listener, never()).onRuleViolation(any());
verify(listener, times(1)).onSuppressedRuleViolation(any());
}
@Test
void testEquals1() {
MyRule r = new MyRule();
assertFalse(r.equals(null), "A rule is never equals to null!");
}
@Test
void testEquals2() {
MyRule r = new MyRule();
assertEquals(r, r, "A rule must be equals to itself");
}
@Test
void testEquals3() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
assertEquals(r1, r2, "Two instances of the same rule are equal");
assertEquals(r1.hashCode(), r2.hashCode(), "Hashcode for two instances of the same rule must be equal");
}
@Test
void testEquals4() {
MyRule myRule = new MyRule();
assertFalse(myRule.equals("MyRule"), "A rule cannot be equal to an object of another class");
}
@Test
void testEquals5() {
MyRule myRule = new MyRule();
MyOtherRule myOtherRule = new MyOtherRule();
assertFalse(myRule.equals(myOtherRule), "Two rules from different classes cannot be equal");
}
@Test
void testEquals6() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setName("MyRule2");
assertFalse(r1.equals(r2), "Rules with different names cannot be equal");
}
@Test
void testEquals7() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setPriority(RulePriority.HIGH);
assertFalse(r1.equals(r2), "Rules with different priority levels cannot be equal");
}
@Test
void testEquals8() {
MyRule r1 = new MyRule();
r1.setProperty(MyRule.XPATH_PROPERTY, "something");
MyRule r2 = new MyRule();
r2.setProperty(MyRule.XPATH_PROPERTY, "something else");
assertFalse(r1.equals(r2), "Rules with different properties values cannot be equal");
}
@Test
void testEquals9() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setProperty(MyRule.XPATH_PROPERTY, "something else");
assertFalse(r1.equals(r2), "Rules with different properties cannot be equal");
}
@Test
void testEquals10() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setMessage("another message");
assertEquals(r1, r2, "Rules with different messages are still equal");
assertEquals(r1.hashCode(), r2.hashCode(), "Rules that are equal must have the an equal hashcode");
}
@Test
void twoRulesUsingPatternPropertiesShouldBeEqual() {
class MockRuleWithPatternProperty extends net.sourceforge.pmd.lang.rule.MockRule {
MockRuleWithPatternProperty(String defaultValue) {
super();
definePropertyDescriptor(PropertyFactory.regexProperty("myRegexProperty")
.desc("description")
.defaultValue(defaultValue)
.build());
}
}
assertEquals(new MockRuleWithPatternProperty("abc"), new MockRuleWithPatternProperty("abc"));
assertNotEquals(new MockRuleWithPatternProperty("abc"), new MockRuleWithPatternProperty("def"));
MockRuleWithPatternProperty rule1 = new MockRuleWithPatternProperty("abc");
PropertyDescriptor<Pattern> myRegexProperty1 = (PropertyDescriptor<Pattern>) rule1.getPropertyDescriptor("myRegexProperty");
rule1.setProperty(myRegexProperty1, Pattern.compile("ghi"));
MockRuleWithPatternProperty rule2 = new MockRuleWithPatternProperty("abc");
PropertyDescriptor<Pattern> myRegexProperty2 = (PropertyDescriptor<Pattern>) rule1.getPropertyDescriptor("myRegexProperty");
rule2.setProperty(myRegexProperty2, Pattern.compile("ghi"));
assertEquals(rule1, rule2);
rule2.setProperty(myRegexProperty2, Pattern.compile("jkl"));
assertNotEquals(rule1, rule2);
// the two rules have the same value, one using default, the other using an explicit value.
// they use effectively the same value, although the default values of the properties are different.
assertEquals(new MockRuleWithPatternProperty("jkl"), rule2);
}
@Test
void testDeepCopyRule() {
MyRule r1 = new MyRule();
MyRule r2 = (MyRule) r1.deepCopy();
assertEquals(r1.getDescription(), r2.getDescription());
assertEquals(r1.getExamples(), r2.getExamples());
assertEquals(r1.getExternalInfoUrl(), r2.getExternalInfoUrl());
assertEquals(r1.getLanguage(), r2.getLanguage());
assertEquals(r1.getMaximumLanguageVersion(), r2.getMaximumLanguageVersion());
assertEquals(r1.getMessage(), r2.getMessage());
assertEquals(r1.getMinimumLanguageVersion(), r2.getMinimumLanguageVersion());
assertEquals(r1.getName(), r2.getName());
assertEquals(r1.getPriority(), r2.getPriority());
assertEquals(r1.getPropertyDescriptors(), r2.getPropertyDescriptors());
assertEquals(r1.getRuleClass(), r2.getRuleClass());
assertEquals(r1.getRuleSetName(), r2.getRuleSetName());
assertEquals(r1.getSince(), r2.getSince());
assertEquals(r1.isPropertyOverridden(MyRule.FOO_DEFAULT_PROPERTY),
r2.isPropertyOverridden(MyRule.FOO_DEFAULT_PROPERTY));
}
}
| 10,789 | 40.183206 | 161 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetSchemaTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class RuleSetSchemaTest {
private ErrorHandler errorHandler;
@BeforeEach
void setUp() {
Locale.setDefault(Locale.ROOT);
errorHandler = mock(ErrorHandler.class);
}
@Test
void verifyVersion2() throws Exception {
String ruleset = generateRuleSet("2.0.0");
Document doc = parseWithVersion2(ruleset);
assertNotNull(doc);
Mockito.verifyNoInteractions(errorHandler);
assertEquals("Custom ruleset", ((Attr) doc.getElementsByTagName("ruleset").item(0).getAttributes().getNamedItem("name")).getValue());
}
@Test
void validateOnly() throws Exception {
Validator validator = PMDRuleSetEntityResolver.getSchemaVersion2().newValidator();
validator.setErrorHandler(errorHandler);
validator.validate(new StreamSource(new ByteArrayInputStream(generateRuleSet("2.0.0").getBytes(StandardCharsets.UTF_8))));
Mockito.verifyNoInteractions(errorHandler);
}
private Document parseWithVersion2(String ruleset) throws SAXException, ParserConfigurationException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature("http://apache.org/xml/features/validation/schema", true);
DocumentBuilder builder = dbf.newDocumentBuilder();
builder.setErrorHandler(errorHandler);
builder.setEntityResolver(new PMDRuleSetEntityResolver());
return builder.parse(new ByteArrayInputStream(ruleset.getBytes(StandardCharsets.UTF_8)));
}
private String generateRuleSet(String version) {
String versionUnderscore = version.replaceAll("\\.", "_");
return "<?xml version=\"1.0\"?>\n"
+ "<ruleset \n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/" + version + "\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/ruleset/" + version
+ " https://pmd.sourceforge.io/ruleset_" + versionUnderscore + ".xsd\"\n"
+ " name=\"Custom ruleset\" >\n"
+ " <description>\n"
+ " This ruleset checks my code for bad stuff\n"
+ " </description>\n"
+ " <rule name=\"DummyBasicMockRule\" language=\"dummy\" since=\"1.0\" message=\"Test Rule 1\"\n"
+ " class=\"net.sourceforge.pmd.lang.rule.MockRule\"\n"
+ " externalInfoUrl=\"${pmd.website.baseurl}/rules/dummy/basic.xml#DummyBasicMockRule\"\n"
+ " >\n"
+ " <description>\n"
+ " Just for test\n"
+ " </description>\n"
+ " <priority>3</priority>\n"
+ " <example>\n"
+ " <![CDATA[\n"
+ " ]]>\n"
+ " </example>\n"
+ " </rule>\n"
+ " <rule ref=\"rulesets/dummy/basic.xml#DummyBasicMockRule\"/>\n"
+ "</ruleset>\n";
}
public static class PMDRuleSetEntityResolver implements EntityResolver {
private static URL schema2 = PMDRuleSetEntityResolver.class.getResource("/ruleset_2_0_0.xsd");
private static SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
if ("https://pmd.sourceforge.io/ruleset_2_0_0.xsd".equals(systemId)) {
return new InputSource(schema2.toExternalForm());
}
throw new IllegalArgumentException("Unable to resolve entity (publicId=" + publicId + ", systemId=" + systemId + ")");
}
public static Schema getSchemaVersion2() throws SAXException {
return schemaFactory.newSchema(schema2);
}
}
}
| 4,969 | 39.737705 | 141 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/PmdConfigurationTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.cache.FileAnalysisCache;
import net.sourceforge.pmd.cache.NoopAnalysisCache;
import net.sourceforge.pmd.internal.util.ClasspathClassLoader;
import net.sourceforge.pmd.renderers.CSVRenderer;
import net.sourceforge.pmd.renderers.Renderer;
class PmdConfigurationTest {
@Test
void testSuppressMarker() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(PMDConfiguration.DEFAULT_SUPPRESS_MARKER, configuration.getSuppressMarker(), "Default suppress marker");
configuration.setSuppressMarker("CUSTOM_MARKER");
assertEquals("CUSTOM_MARKER", configuration.getSuppressMarker(), "Changed suppress marker");
}
@Test
void testThreads() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(Runtime.getRuntime().availableProcessors(), configuration.getThreads(), "Default threads");
configuration.setThreads(0);
assertEquals(0, configuration.getThreads(), "Changed threads");
}
@Test
void testClassLoader() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(PMDConfiguration.class.getClassLoader(), configuration.getClassLoader(), "Default ClassLoader");
configuration.prependAuxClasspath("some.jar");
assertEquals(ClasspathClassLoader.class, configuration.getClassLoader().getClass(),
"Prepended ClassLoader class");
URL[] urls = ((ClasspathClassLoader) configuration.getClassLoader()).getURLs();
assertEquals(1, urls.length, "urls length");
assertTrue(urls[0].toString().endsWith("/some.jar"), "url[0]");
assertEquals(PMDConfiguration.class.getClassLoader(), configuration.getClassLoader().getParent(),
"parent classLoader");
configuration.setClassLoader(null);
assertEquals(PMDConfiguration.class.getClassLoader(), configuration.getClassLoader(),
"Revert to default ClassLoader");
}
@Test
void auxClasspathWithRelativeFileEmpty() {
String relativeFilePath = "src/test/resources/net/sourceforge/pmd/cli/auxclasspath-empty.cp";
PMDConfiguration configuration = new PMDConfiguration();
configuration.prependAuxClasspath("file:" + relativeFilePath);
URL[] urls = ((ClasspathClassLoader) configuration.getClassLoader()).getURLs();
assertEquals(0, urls.length);
}
@Test
void auxClasspathWithRelativeFileEmpty2() {
String relativeFilePath = "./src/test/resources/net/sourceforge/pmd/cli/auxclasspath-empty.cp";
PMDConfiguration configuration = new PMDConfiguration();
configuration.prependAuxClasspath("file:" + relativeFilePath);
URL[] urls = ((ClasspathClassLoader) configuration.getClassLoader()).getURLs();
assertEquals(0, urls.length);
}
@Test
void auxClasspathWithRelativeFile() throws URISyntaxException {
final String FILE_SCHEME = "file";
String currentWorkingDirectory = new File("").getAbsoluteFile().toURI().getPath();
String relativeFilePath = "src/test/resources/net/sourceforge/pmd/cli/auxclasspath.cp";
PMDConfiguration configuration = new PMDConfiguration();
configuration.prependAuxClasspath("file:" + relativeFilePath);
URL[] urls = ((ClasspathClassLoader) configuration.getClassLoader()).getURLs();
URI[] uris = new URI[urls.length];
for (int i = 0; i < urls.length; i++) {
uris[i] = urls[i].toURI();
}
URI[] expectedUris = new URI[] {
new URI(FILE_SCHEME, null, currentWorkingDirectory + "lib1.jar", null),
new URI(FILE_SCHEME, null, currentWorkingDirectory + "other/directory/lib2.jar", null),
new URI(FILE_SCHEME, null, new File("/home/jondoe/libs/lib3.jar").getAbsoluteFile().toURI().getPath(), null),
new URI(FILE_SCHEME, null, currentWorkingDirectory + "classes", null),
new URI(FILE_SCHEME, null, currentWorkingDirectory + "classes2", null),
new URI(FILE_SCHEME, null, new File("/home/jondoe/classes").getAbsoluteFile().toURI().getPath(), null),
new URI(FILE_SCHEME, null, currentWorkingDirectory, null),
new URI(FILE_SCHEME, null, currentWorkingDirectory + "relative source dir/bar", null),
};
assertArrayEquals(expectedUris, uris);
}
@Test
void testRuleSetsLegacy() {
PMDConfiguration configuration = new PMDConfiguration();
assertNull(configuration.getRuleSets(), "Default RuleSets");
configuration.setRuleSets("/rulesets/basic.xml");
assertEquals("/rulesets/basic.xml", configuration.getRuleSets(), "Changed RuleSets");
configuration.setRuleSets((String) null);
assertNull(configuration.getRuleSets());
}
@Test
void testRuleSets() {
PMDConfiguration configuration = new PMDConfiguration();
assertThat(configuration.getRuleSetPaths(), empty());
configuration.setRuleSets(listOf("/rulesets/basic.xml"));
assertEquals(listOf("/rulesets/basic.xml"), configuration.getRuleSetPaths());
configuration.addRuleSet("foo.xml");
assertEquals(listOf("/rulesets/basic.xml", "foo.xml"), configuration.getRuleSetPaths());
configuration.setRuleSets(Collections.<String>emptyList());
assertThat(configuration.getRuleSetPaths(), empty());
// should be addable even though we set it to an unmodifiable empty list
configuration.addRuleSet("foo.xml");
assertEquals(listOf("foo.xml"), configuration.getRuleSetPaths());
}
@Test
void testMinimumPriority() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(RulePriority.LOW, configuration.getMinimumPriority(), "Default minimum priority");
configuration.setMinimumPriority(RulePriority.HIGH);
assertEquals(RulePriority.HIGH, configuration.getMinimumPriority(), "Changed minimum priority");
}
@Test
void testSourceEncoding() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(System.getProperty("file.encoding"), configuration.getSourceEncoding().name(), "Default source encoding");
configuration.setSourceEncoding(StandardCharsets.UTF_16LE.name());
assertEquals(StandardCharsets.UTF_16LE, configuration.getSourceEncoding(), "Changed source encoding");
}
@Test
void testInputPaths() {
PMDConfiguration configuration = new PMDConfiguration();
assertThat(configuration.getInputPathList(), empty());
configuration.setInputPaths("a,b,c");
List<Path> expected = listOf(
Paths.get("a"), Paths.get("b"), Paths.get("c")
);
assertEquals(expected, configuration.getInputPathList(), "Changed input paths");
}
@Test
void testReportFormat() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(null, configuration.getReportFormat(), "Default report format");
configuration.setReportFormat("csv");
assertEquals("csv", configuration.getReportFormat(), "Changed report format");
}
@Test
void testCreateRenderer() {
PMDConfiguration configuration = new PMDConfiguration();
configuration.setReportFormat("csv");
Renderer renderer = configuration.createRenderer();
assertEquals(CSVRenderer.class, renderer.getClass(), "Renderer class");
assertEquals(false, renderer.isShowSuppressedViolations(), "Default renderer show suppressed violations");
configuration.setShowSuppressedViolations(true);
renderer = configuration.createRenderer();
assertEquals(CSVRenderer.class, renderer.getClass(), "Renderer class");
assertEquals(true, renderer.isShowSuppressedViolations(), "Changed renderer show suppressed violations");
}
@Test
void testReportFile() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(null, configuration.getReportFile(), "Default report file");
configuration.setReportFile("somefile");
assertEquals("somefile", configuration.getReportFile(), "Changed report file");
}
@Test
void testShowSuppressedViolations() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(false, configuration.isShowSuppressedViolations(), "Default show suppressed violations");
configuration.setShowSuppressedViolations(true);
assertEquals(true, configuration.isShowSuppressedViolations(), "Changed show suppressed violations");
}
@Test
void testReportProperties() {
PMDConfiguration configuration = new PMDConfiguration();
assertEquals(0, configuration.getReportProperties().size(), "Default report properties size");
configuration.getReportProperties().put("key", "value");
assertEquals(1, configuration.getReportProperties().size(), "Changed report properties size");
assertEquals("value", configuration.getReportProperties().get("key"), "Changed report properties value");
configuration.setReportProperties(new Properties());
assertEquals(0, configuration.getReportProperties().size(), "Replaced report properties size");
}
@Test
void testAnalysisCache(@TempDir Path folder) throws IOException {
final PMDConfiguration configuration = new PMDConfiguration();
assertNotNull(configuration.getAnalysisCache(), "Default cache is null");
assertTrue(configuration.getAnalysisCache() instanceof NoopAnalysisCache, "Default cache is not a noop");
configuration.setAnalysisCache(null);
assertNotNull(configuration.getAnalysisCache(), "Default cache was set to null");
final File cacheFile = folder.resolve("pmd-cachefile").toFile();
assertTrue(cacheFile.createNewFile());
final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile);
configuration.setAnalysisCache(analysisCache);
assertSame(analysisCache, configuration.getAnalysisCache(), "Configured cache not stored");
}
@Test
void testAnalysisCacheLocation() {
final PMDConfiguration configuration = new PMDConfiguration();
configuration.setAnalysisCacheLocation(null);
assertNotNull(configuration.getAnalysisCache(), "Null cache location accepted");
assertTrue(configuration.getAnalysisCache() instanceof NoopAnalysisCache, "Null cache location accepted");
configuration.setAnalysisCacheLocation("pmd.cache");
assertNotNull(configuration.getAnalysisCache(), "Not null cache location produces null cache");
assertTrue(configuration.getAnalysisCache() instanceof FileAnalysisCache,
"File cache location doesn't produce a file cache");
}
@Test
void testIgnoreIncrementalAnalysis(@TempDir Path folder) throws IOException {
final PMDConfiguration configuration = new PMDConfiguration();
// set dummy cache location
final File cacheFile = folder.resolve("pmd-cachefile").toFile();
assertTrue(cacheFile.createNewFile());
final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile);
configuration.setAnalysisCache(analysisCache);
assertNotNull(configuration.getAnalysisCache(), "Null cache location accepted");
assertFalse(configuration.getAnalysisCache() instanceof NoopAnalysisCache, "Non null cache location, cache should not be noop");
configuration.setIgnoreIncrementalAnalysis(true);
assertTrue(configuration.getAnalysisCache() instanceof NoopAnalysisCache, "Ignoring incremental analysis should turn the cache into a noop");
}
}
| 12,833 | 47.430189 | 149 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/FooRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
/**
* Sample rule that detect any node with an image of "Foo". Used for testing.
*/
public class FooRule extends AbstractRule {
public FooRule() {
setName("Foo");
setDescription("Description with Unicode Character U+2013: \u2013 .");
setLanguage(DummyLanguageModule.getInstance());
}
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forXPathNames(setOf("dummyNode", "dummyRootNode"));
}
@Override
public String getMessage() {
return "blah";
}
@Override
public String getRuleSetName() {
return "RuleSet";
}
@Override
public void apply(Node node, RuleContext ctx) {
for (int i = 0; i < node.getNumChildren(); i++) {
apply(node.getChild(i), ctx);
}
if ("Foo".equals(node.getImage())) {
addViolation(ctx, node);
}
}
}
| 1,375 | 25.461538 | 85 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import net.sourceforge.pmd.RuleSetTest.MockRule;
import net.sourceforge.pmd.lang.Dummy2LanguageModule;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.SimpleTestTextFile;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.reporting.ReportStats;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* @author Clément Fournier
*/
class PmdAnalysisTest {
@Test
void testPmdAnalysisWithEmptyConfig() {
PMDConfiguration config = new PMDConfiguration();
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
assertThat(pmd.files().getCollectedFiles(), empty());
assertThat(pmd.rulesets(), empty());
assertThat(pmd.renderers(), empty());
}
}
@Test
void testRendererInteractions() throws IOException {
PMDConfiguration config = new PMDConfiguration();
config.setInputPaths("sample-source/dummy");
Renderer renderer = spy(Renderer.class);
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRenderer(renderer);
verify(renderer, never()).start();
pmd.performAnalysis();
}
verify(renderer, times(1)).renderFileReport(ArgumentMatchers.<Report>any());
verify(renderer, times(1)).start();
verify(renderer, times(1)).end();
verify(renderer, times(1)).flush();
}
@Test
void testRulesetLoading() {
PMDConfiguration config = new PMDConfiguration();
config.addRuleSet("rulesets/dummy/basic.xml");
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
assertThat(pmd.rulesets(), hasSize(1));
}
}
@Test
void testRulesetWhenSomeoneHasAnError() {
PMDConfiguration config = new PMDConfiguration();
config.addRuleSet("rulesets/dummy/basic.xml");
config.addRuleSet("rulesets/xxxe/notaruleset.xml");
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
assertThat(pmd.rulesets(), hasSize(1)); // no failure
assertThat(pmd.getReporter().numErrors(), equalTo(1));
}
}
@Test
void testParseException() {
PMDConfiguration config = new PMDConfiguration();
config.setThreads(1);
config.setForceLanguageVersion(DummyLanguageModule.getInstance().getVersionWhereParserThrows());
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRuleSet(RuleSet.forSingleRule(new MockRule()));
pmd.files().addSourceFile(FileId.fromPathLikeString("file"), "some source");
ReportStats stats = pmd.runAndReturnStats();
assertEquals(1, stats.getNumErrors(), "Errors");
assertEquals(0, stats.getNumViolations(), "Violations");
}
}
@Test
void testRuleFailureDuringInitialization() {
PMDConfiguration config = new PMDConfiguration();
config.setThreads(1);
MessageReporter mockReporter = spy(MessageReporter.quiet());
config.setReporter(mockReporter);
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRuleSet(RuleSet.forSingleRule(new MockRule() {
@Override
public void initialize(LanguageProcessor languageProcessor) {
throw new IllegalStateException();
}
}));
pmd.files().addSourceFile(FileId.fromPathLikeString("fname1.dummy"), "some source");
ReportStats stats = pmd.runAndReturnStats();
// the error number here is only for FileAnalysisException, so
// the exception during initialization is not counted.
assertEquals(0, stats.getNumErrors(), "Errors");
assertEquals(0, stats.getNumViolations(), "Violations");
verify(mockReporter).errorEx(Mockito.contains("init"), any(IllegalStateException.class));
}
}
@Test
void testFileWithSpecificLanguage() {
final Language language = Dummy2LanguageModule.getInstance();
PMDConfiguration config = new PMDConfiguration();
config.setIgnoreIncrementalAnalysis(true);
RuleSet ruleset = RuleSet.forSingleRule(new TestRule());
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRuleSet(ruleset);
pmd.files().addFile(Paths.get("src", "test", "resources", "sample-source", "dummy", "foo.txt"), language);
Report report = pmd.performAnalysisAndCollectReport();
for (Report.ProcessingError error : report.getProcessingErrors()) {
System.out.println("error = " + error.getMsg() + ": " + error.getDetail());
}
assertEquals(0, report.getProcessingErrors().size());
assertEquals(1, report.getViolations().size());
}
}
@Test
void testTextFileWithSpecificLanguage() {
final Language language = Dummy2LanguageModule.getInstance();
PMDConfiguration config = new PMDConfiguration();
config.setIgnoreIncrementalAnalysis(true);
RuleSet ruleset = RuleSet.forSingleRule(new TestRule());
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.addRuleSet(ruleset);
pmd.files().addFile(new SimpleTestTextFile("test content foo", FileId.fromPathLikeString("foo.txt"), language.getDefaultVersion()));
Report report = pmd.performAnalysisAndCollectReport();
for (Report.ProcessingError error : report.getProcessingErrors()) {
System.out.println("error = " + error.getMsg() + ": " + error.getDetail());
}
assertEquals(0, report.getProcessingErrors().size());
assertEquals(1, report.getViolations().size());
}
}
private static class TestRule extends AbstractRule {
TestRule() {
setLanguage(Dummy2LanguageModule.getInstance());
setMessage("dummy 2 test rule");
}
@Override
public void apply(Node node, RuleContext ctx) {
ctx.addViolation(node);
}
}
}
| 7,079 | 37.901099 | 144 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetReferenceIdTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.head;
import static com.github.tomakehurst.wiremock.client.WireMock.headRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
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.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.util.ResourceLoader;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
@WireMockTest
class RuleSetReferenceIdTest {
private static void assertRuleSetReferenceId(final boolean expectedExternal, final String expectedRuleSetFileName,
final boolean expectedAllRules, final String expectedRuleName, final String expectedToString,
final RuleSetReferenceId reference) {
assertEquals(expectedExternal, reference.isExternal(), "Wrong external");
assertEquals(expectedRuleSetFileName, reference.getRuleSetFileName(), "Wrong RuleSet file name");
assertEquals(expectedAllRules, reference.isAllRules(), "Wrong all Rule reference");
assertEquals(expectedRuleName, reference.getRuleName(), "Wrong Rule name");
assertEquals(expectedToString, reference.toString(), "Wrong toString()");
}
@Test
void testCommaInSingleId() {
assertThrows(IllegalArgumentException.class, () -> new RuleSetReferenceId("bad,id"));
}
@Test
void testInternalWithInternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("SomeRule", new RuleSetReferenceId("SomeOtherRule")));
}
@Test
void testExternalWithExternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("someruleset.xml/SomeOtherRule")));
}
@Test
void testExternalWithInternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("SomeOtherRule")));
}
@Test
void testInteralWithExternal() {
// This is okay
new RuleSetReferenceId("SomeRule", new RuleSetReferenceId("someruleset.xml/SomeOtherRule"));
}
@Test
void testEmptyRuleSet() {
// This is representative of how the Test framework creates
// RuleSetReferenceId from static RuleSet XMLs
RuleSetReferenceId reference = new RuleSetReferenceId(null);
assertRuleSetReferenceId(true, null, true, null, "anonymous all Rule", reference);
}
@Test
void testInternalWithExternalRuleSet() {
// This is representative of how the RuleSetFactory temporarily pairs an
// internal reference
// with an external reference.
RuleSetReferenceId internalRuleSetReferenceId = new RuleSetReferenceId("MockRuleName");
assertRuleSetReferenceId(false, null, false, "MockRuleName", "MockRuleName", internalRuleSetReferenceId);
RuleSetReferenceId externalRuleSetReferenceId = new RuleSetReferenceId("rulesets/java/basic.xml");
assertRuleSetReferenceId(true, "rulesets/java/basic.xml", true, null, "rulesets/java/basic.xml",
externalRuleSetReferenceId);
RuleSetReferenceId pairRuleSetReferenceId = new RuleSetReferenceId("MockRuleName", externalRuleSetReferenceId);
assertRuleSetReferenceId(true, "rulesets/java/basic.xml", false, "MockRuleName",
"rulesets/java/basic.xml/MockRuleName", pairRuleSetReferenceId);
}
@Test
void testConstructorGivenHttpUrlIdSucceedsAndProcessesIdCorrectly() {
final String sonarRulesetUrlId = "http://localhost:54321/profiles/export?format=pmd&language=java&name=Sonar%2520way";
RuleSetReferenceId ruleSetReferenceId = new RuleSetReferenceId(" " + sonarRulesetUrlId + " ");
assertRuleSetReferenceId(true, sonarRulesetUrlId, true, null, sonarRulesetUrlId, ruleSetReferenceId);
}
@Test
void testConstructorGivenHttpUrlInputStream(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {
String path = "/profiles/export?format=pmd&language=java&name=Sonar%2520way";
String rulesetUrl = "http://localhost:" + wmRuntimeInfo.getHttpPort() + path;
stubFor(head(urlEqualTo(path)).willReturn(aResponse().withStatus(200)));
stubFor(get(urlEqualTo(path))
.willReturn(aResponse().withStatus(200).withHeader("Content-type", "text/xml").withBody("xyz")));
RuleSetReferenceId ruleSetReferenceId = new RuleSetReferenceId(" " + rulesetUrl + " ");
assertRuleSetReferenceId(true, rulesetUrl, true, null, rulesetUrl, ruleSetReferenceId);
try (InputStream inputStream = ruleSetReferenceId.getInputStream(new ResourceLoader())) {
String loaded = IOUtil.readToString(inputStream, StandardCharsets.UTF_8);
assertEquals("xyz", loaded);
}
verify(1, headRequestedFor(urlEqualTo(path)));
verify(0, headRequestedFor(urlEqualTo("/profiles")));
verify(1, getRequestedFor(urlEqualTo(path)));
assertEquals(1, findAll(headRequestedFor(urlMatching(".*"))).size());
assertEquals(1, findAll(getRequestedFor(urlMatching(".*"))).size());
}
@Test
void testConstructorGivenHttpUrlSingleRuleInputStream(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {
String path = "/profiles/export?format=pmd&language=java&name=Sonar%2520way";
String completePath = path + "/DummyBasicMockRule";
String hostpart = "http://localhost:" + wmRuntimeInfo.getHttpPort();
String basicRuleSet = IOUtil
.readToString(RuleSetReferenceId.class.getResourceAsStream("/rulesets/dummy/basic.xml"), StandardCharsets.UTF_8);
stubFor(head(urlEqualTo(completePath)).willReturn(aResponse().withStatus(404)));
stubFor(head(urlEqualTo(path)).willReturn(aResponse().withStatus(200).withHeader("Content-type", "text/xml")));
stubFor(get(urlEqualTo(path))
.willReturn(aResponse().withStatus(200).withHeader("Content-type", "text/xml").withBody(basicRuleSet)));
RuleSetReferenceId ruleSetReferenceId = new RuleSetReferenceId(" " + hostpart + completePath + " ");
assertRuleSetReferenceId(true, hostpart + path, false, "DummyBasicMockRule", hostpart + completePath,
ruleSetReferenceId);
try (InputStream inputStream = ruleSetReferenceId.getInputStream(new ResourceLoader())) {
String loaded = IOUtil.readToString(inputStream, StandardCharsets.UTF_8);
assertEquals(basicRuleSet, loaded);
}
verify(1, headRequestedFor(urlEqualTo(completePath)));
verify(1, headRequestedFor(urlEqualTo(path)));
verify(1, getRequestedFor(urlEqualTo(path)));
verify(0, getRequestedFor(urlEqualTo(completePath)));
assertEquals(2, findAll(headRequestedFor(urlMatching(".*"))).size());
assertEquals(1, findAll(getRequestedFor(urlMatching(".*"))).size());
}
@Test
void testOneSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
references.get(0));
}
@Test
void testMultipleSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-unusedcode,dummy-basic");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/unusedcode.xml", true, null, "rulesets/dummy/unusedcode.xml",
references.get(0));
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
references.get(1));
}
/**
* See https://sourceforge.net/p/pmd/bugs/1201/
*/
@Test
void testMultipleRulesWithSpaces() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic, dummy-unusedcode, dummy2-basic");
assertEquals(3, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
references.get(0));
assertRuleSetReferenceId(true, "rulesets/dummy/unusedcode.xml", true, null, "rulesets/dummy/unusedcode.xml",
references.get(1));
assertRuleSetReferenceId(true, "rulesets/dummy2/basic.xml", true, null, "rulesets/dummy2/basic.xml",
references.get(2));
}
@Test
void testOneReleaseRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("50");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/releases/50.xml", true, null, "rulesets/releases/50.xml",
references.get(0));
}
@Test
void testOneFullRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/java/unusedcode.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/java/unusedcode.xml", true, null, "rulesets/java/unusedcode.xml",
references.get(0));
}
@Test
void testOneFullRuleSetURL() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("file://somepath/rulesets/java/unusedcode.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "file://somepath/rulesets/java/unusedcode.xml", true, null,
"file://somepath/rulesets/java/unusedcode.xml", references.get(0));
}
@Test
void testMultipleFullRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId
.parse("rulesets/java/unusedcode.xml,rulesets/java/basic.xml");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/java/unusedcode.xml", true, null, "rulesets/java/unusedcode.xml",
references.get(0));
assertRuleSetReferenceId(true, "rulesets/java/basic.xml", true, null, "rulesets/java/basic.xml",
references.get(1));
}
@Test
void testMixRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/dummy/unusedcode.xml,dummy2-basic");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/unusedcode.xml", true, null, "rulesets/dummy/unusedcode.xml",
references.get(0));
assertRuleSetReferenceId(true, "rulesets/dummy2/basic.xml", true, null, "rulesets/dummy2/basic.xml",
references.get(1));
}
@Test
void testUnknownRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("nonexistant.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "nonexistant.xml", true, null, "nonexistant.xml", references.get(0));
}
@Test
void testUnknownAndSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic,nonexistant.xml");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
references.get(0));
assertRuleSetReferenceId(true, "nonexistant.xml", true, null, "nonexistant.xml", references.get(1));
}
@Test
void testSimpleRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic/DummyBasicMockRule");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", false, "DummyBasicMockRule",
"rulesets/dummy/basic.xml/DummyBasicMockRule", references.get(0));
}
@Test
void testFullRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/java/basic.xml/EmptyCatchBlock");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/java/basic.xml", false, "EmptyCatchBlock",
"rulesets/java/basic.xml/EmptyCatchBlock", references.get(0));
}
@Test
void testFullRuleSetURLAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId
.parse("file://somepath/rulesets/java/unusedcode.xml/EmptyCatchBlock");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "file://somepath/rulesets/java/unusedcode.xml", false, "EmptyCatchBlock",
"file://somepath/rulesets/java/unusedcode.xml/EmptyCatchBlock", references.get(0));
}
@Test
void testInternalRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("EmptyCatchBlock");
assertEquals(1, references.size());
assertRuleSetReferenceId(false, null, false, "EmptyCatchBlock", "EmptyCatchBlock", references.get(0));
}
@Test
void testRelativePathRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("pmd/pmd-ruleset.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "pmd/pmd-ruleset.xml", true, null, "pmd/pmd-ruleset.xml", references.get(0));
}
@Test
void testAbsolutePathRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("/home/foo/pmd/pmd-ruleset.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "/home/foo/pmd/pmd-ruleset.xml", true, null, "/home/foo/pmd/pmd-ruleset.xml",
references.get(0));
}
@Test
void testFooRules() throws Exception {
String fooRulesFile = new File("./src/test/resources/net/sourceforge/pmd/rulesets/foo-project/foo-rules")
.getCanonicalPath();
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(fooRulesFile);
assertEquals(1, references.size());
assertRuleSetReferenceId(true, fooRulesFile, true, null, fooRulesFile, references.get(0));
}
@Test
void testNullRulesetString() throws Exception {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(null);
assertTrue(references.isEmpty());
}
}
| 15,203 | 46.5125 | 129 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static net.sourceforge.pmd.internal.util.FileCollectionUtil.collectFileList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.internal.util.FileCollectionUtil;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.document.FileCollector;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.util.log.MessageReporter;
class PMDFilelistTest {
private static final Path RESOURCES = Paths.get("src/test/resources/net/sourceforge/pmd/cli/");
private @NonNull FileCollector newCollector() {
return FileCollector.newCollector(new LanguageVersionDiscoverer(LanguageRegistry.PMD), MessageReporter.quiet());
}
@Test
void testGetApplicableFiles() {
FileCollector collector = newCollector();
collectFileList(collector, RESOURCES.resolve("filelist.txt"));
List<TextFile> applicableFiles = collector.getCollectedFiles();
assertThat(applicableFiles, hasSize(2));
assertThat(applicableFiles.get(0).getFileId().getFileName(), equalTo("anotherfile.dummy"));
assertThat(applicableFiles.get(1).getFileId().getFileName(), equalTo("somefile.dummy"));
}
@Test
void testGetApplicableFilesMultipleLines() {
FileCollector collector = newCollector();
collectFileList(collector, RESOURCES.resolve("filelist2.txt"));
List<TextFile> applicableFiles = collector.getCollectedFiles();
// note: the file has 3 entries, but one is duplicated, resulting in 2 individual files
assertThat(applicableFiles, hasSize(2));
assertFilenameIs(applicableFiles.get(0), "anotherfile.dummy");
assertFilenameIs(applicableFiles.get(1), "somefile.dummy");
}
private static void assertFilenameIs(TextFile textFile, String suffix) {
assertThat(textFile.getFileId().getFileName(), is(suffix));
}
@Test
void testGetApplicableFilesWithIgnores() {
FileCollector collector = newCollector();
PMDConfiguration configuration = new PMDConfiguration();
configuration.setInputFilePath(RESOURCES.resolve("filelist3.txt"));
configuration.setIgnoreFilePath(RESOURCES.resolve("ignorelist.txt"));
FileCollectionUtil.collectFiles(configuration, collector);
List<TextFile> applicableFiles = collector.getCollectedFiles();
assertThat(applicableFiles, hasSize(2));
assertFilenameIs(applicableFiles.get(0), "somefile2.dummy");
assertFilenameIs(applicableFiles.get(1), "somefile4.dummy");
}
@Test
void testRelativizeWith() {
PMDConfiguration conf = new PMDConfiguration();
conf.setInputFilePath(RESOURCES.resolve("filelist2.txt"));
conf.addRelativizeRoot(Paths.get("src/test/resources"));
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(2));
assertHasName(files.get(0), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/anotherfile.dummy"), pmd);
assertHasName(files.get(1), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/somefile.dummy"), pmd);
}
}
public static void assertHasName(TextFile textFile, String expected, PmdAnalysis pmd) {
assertThat(pmd.fileNameRenderer().getDisplayName(textFile), equalTo(expected));
}
@Test
void testRelativizeWithOtherDir() {
PMDConfiguration conf = new PMDConfiguration();
conf.setInputFilePath(RESOURCES.resolve("filelist4.txt"));
conf.addRelativizeRoot(RESOURCES.resolve("src"));
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertHasName(files.get(0), ".." + IOUtil.normalizePath("/otherSrc/somefile.dummy"), pmd);
assertHasName(files.get(1), "anotherfile.dummy", pmd);
assertHasName(files.get(2), "somefile.dummy", pmd);
}
}
@Test
void testRelativizeWithSeveralDirs() {
PMDConfiguration conf = new PMDConfiguration();
conf.setInputFilePath(RESOURCES.resolve("filelist4.txt"));
conf.addRelativizeRoot(RESOURCES.resolve("src"));
conf.addRelativizeRoot(RESOURCES.resolve("otherSrc"));
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertHasName(files.get(0), "somefile.dummy", pmd);
assertHasName(files.get(1), "anotherfile.dummy", pmd);
assertHasName(files.get(2), "somefile.dummy", pmd);
}
}
@Test
void testUseAbsolutePaths() {
PMDConfiguration conf = new PMDConfiguration();
conf.setInputFilePath(RESOURCES.resolve("filelist4.txt"));
conf.addRelativizeRoot(RESOURCES.toAbsolutePath().getRoot());
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertHasName(files.get(0), RESOURCES.resolve("otherSrc/somefile.dummy").toAbsolutePath().toString(), pmd);
assertHasName(files.get(1), RESOURCES.resolve("src/anotherfile.dummy").toAbsolutePath().toString(), pmd);
assertHasName(files.get(2), RESOURCES.resolve("src/somefile.dummy").toAbsolutePath().toString(), pmd);
}
}
@Test
void testGetApplicableFilesWithDirAndIgnores() {
PMDConfiguration configuration = new PMDConfiguration();
configuration.addInputPath(RESOURCES.resolve("src"));
configuration.setIgnoreFilePath(RESOURCES.resolve("ignorelist.txt"));
FileCollector collector = newCollector();
FileCollectionUtil.collectFiles(configuration, collector);
List<TextFile> applicableFiles = collector.getCollectedFiles();
assertThat(applicableFiles, hasSize(4));
assertFilenameIs(applicableFiles.get(0), "anotherfile.dummy");
assertFilenameIs(applicableFiles.get(1), "somefile.dummy");
assertFilenameIs(applicableFiles.get(2), "somefile2.dummy");
assertFilenameIs(applicableFiles.get(3), "somefile4.dummy");
}
}
| 6,927 | 42.031056 | 120 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static net.sourceforge.pmd.cli.PMDFilelistTest.assertHasName;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.URI;
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.PmdAnalysis;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.document.TextFile;
class ZipFileTest {
private static final String ZIP_PATH = "src/test/resources/net/sourceforge/pmd/cli/zipWithSources.zip";
private final Path zipPath = Paths.get(ZIP_PATH);
@Test
void testZipFile() {
PMDConfiguration conf = new PMDConfiguration();
conf.addInputPath(zipPath);
// no relativizeRoot paths configured -> we use the relative path
String reportPath = zipPath.toString();
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd);
assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd);
assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd);
}
}
@Test
void testZipFileIds() throws IOException {
PMDConfiguration conf = new PMDConfiguration();
// no relativizeRoot paths configured -> we use the relative path
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
pmd.files().addZipFileWithContent(zipPath);
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertThat(files.get(0).getFileId().getUriString(),
equalTo("jar:" + zipPath.toUri() + "!/otherSrc/somefile.dummy"));
}
}
@Test
void testZipFileRelativizeWith() {
PMDConfiguration conf = new PMDConfiguration();
conf.addInputPath(zipPath);
conf.addRelativizeRoot(Paths.get("src/test/resources"));
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
String baseZipPath = IOUtil.normalizePath("net/sourceforge/pmd/cli/zipWithSources.zip");
assertHasName(files.get(0), baseZipPath + "!/otherSrc/somefile.dummy", pmd);
assertHasName(files.get(1), baseZipPath + "!/src/somefile.dummy", pmd);
assertHasName(files.get(2), baseZipPath + "!/src/somefile1.dummy", pmd);
}
}
@Test
void testZipFileRelativizeWithRoot() {
PMDConfiguration conf = new PMDConfiguration();
conf.addInputPath(zipPath);
// this configures "/" as the relativizeRoot -> result are absolute paths
conf.addRelativizeRoot(zipPath.toAbsolutePath().getRoot());
String reportPath = zipPath.toAbsolutePath().toString();
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
List<TextFile> files = pmd.files().getCollectedFiles();
assertThat(files, hasSize(3));
assertEquals("/otherSrc/somefile.dummy", files.get(0).getFileId().getAbsolutePath());
URI zipUri = zipPath.toUri();
assertEquals("jar:" + zipUri + "!/otherSrc/somefile.dummy", files.get(0).getFileId().getUriString());
assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd);
assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd);
assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd);
}
}
}
| 4,017 | 40.854167 | 113 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageRegistryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Test;
class LanguageRegistryTest {
private final LanguageRegistry languageRegistry = LanguageRegistry.PMD;
@Test
void getDefaultVersionLanguageTest() {
Language dummy = languageRegistry.getLanguageById("dummy");
LanguageVersion dummy12 = dummy.getVersion("1.2");
assertNotNull(dummy12);
LanguageVersion dummyDefault = dummy.getDefaultVersion();
assertNotNull(dummyDefault);
assertNotSame(dummy12, dummyDefault);
}
@Test
void getLanguageVersionByAliasTest() {
Language dummy = languageRegistry.getLanguageById("dummy");
LanguageVersion dummy17 = dummy.getVersion("1.7");
assertNotNull(dummy17);
assertEquals("1.7", dummy17.getVersion());
LanguageVersion dummy7 = dummy.getVersion("7");
assertNotNull(dummy7);
assertEquals("1.7", dummy17.getVersion());
assertSame(dummy17, dummy7);
}
}
| 1,330 | 29.25 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/DummyLanguageModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import java.util.Objects;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextRegion;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
import net.sourceforge.pmd.reporting.ViolationDecorator;
/**
* Dummy language used for testing PMD.
*/
public class DummyLanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "Dummy";
public static final String TERSE_NAME = "dummy";
private static final String PARSER_THROWS = "parserThrows";
public DummyLanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME).extensions("dummy")
.addVersion("1.0")
.addVersion("1.1")
.addVersion("1.2")
.addVersion("1.3")
.addVersion("1.4")
.addVersion("1.5", "5")
.addVersion("1.6", "6")
.addDefaultVersion("1.7", "7")
.addVersion(PARSER_THROWS)
.addVersion("1.8", "8"), new Handler());
}
public static DummyLanguageModule getInstance() {
return (DummyLanguageModule) Objects.requireNonNull(LanguageRegistry.PMD.getLanguageByFullName(NAME));
}
public LanguageVersion getVersionWhereParserThrows() {
return getVersion(PARSER_THROWS);
}
public static class Handler extends AbstractPmdLanguageVersionHandler {
@Override
public Parser getParser() {
return task -> {
if (task.getLanguageVersion().getVersion().equals(PARSER_THROWS)) {
throw new ParseException("ohio");
}
return readLispNode(task);
};
}
@Override
public ViolationDecorator getViolationDecorator() {
return (node, data) -> data.put(RuleViolation.PACKAGE_NAME, "foo");
}
}
/**
* Creates a tree of nodes that corresponds to the nesting structures
* of parentheses in the text. The image of each node is also populated.
* This is useful to create non-trivial trees with all the relevant
* data (eg coordinates) set properly.
*
* Eg {@code (a(b)x(c))} will create a tree with a node "a", with two
* children "b" and "c". "x" is ignored. The node "a" is not the root
* node, it has a {@link DummyRootNode} as parent, whose image is "".
*/
public static DummyRootNode readLispNode(ParserTask task) {
TextDocument document = task.getTextDocument();
final DummyRootNode root = new DummyRootNode().withTaskInfo(task);
root.setRegion(document.getEntireRegion());
DummyNode top = root;
int lastNodeStart = 0;
Chars text = document.getText();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '(') {
DummyNode node = new DummyNode();
node.setParent(top);
top.addChild(node, top.getNumChildren());
// setup coordinates, temporary (will be completed when node closes)
node.setRegion(TextRegion.caretAt(i));
// cut out image
if (top.getImage() == null) {
// image may be non null if this is not the first child of 'top'
// eg in (a(b)x(c)), the image of the parent is set to "a".
// When we're processing "(c", we ignore "x".
String image = text.substring(lastNodeStart, i);
top.setImage(image);
}
lastNodeStart = i + 1;
// node is the top of the stack now
top = node;
} else if (c == ')') {
if (top == null) {
throw new ParseException("Unbalanced parentheses: " + text);
}
top.setRegion(TextRegion.fromBothOffsets(top.getTextRegion().getStartOffset(), i));
if (top.getImage() == null) {
// cut out image (if node doesn't have children it hasn't been populated yet)
String image = text.substring(lastNodeStart, i);
top.setImage(image);
lastNodeStart = i + 1;
}
top = top.getParent();
}
}
if (top != root) {
throw new ParseException("Unbalanced parentheses: " + text);
}
return root;
}
}
| 5,124 | 38.122137 | 110 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageModuleBaseTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageModuleBase.LanguageMetadata;
/**
* @author Clément Fournier
*/
class LanguageModuleBaseTest {
@Test
void testInvalidId() {
assertInvalidId("");
assertInvalidId("two words");
assertInvalidId("CapitalLetters");
assertInvalidId("C");
assertInvalidId("ab-c");
assertThrows(NullPointerException.class, () -> LanguageMetadata.withId(null));
Exception e = assertThrows(IllegalArgumentException.class, () -> LanguageMetadata.withId("dummy").addVersion(""),
"Empty versions should not be allowed.");
assertEquals("Invalid version name: ''", e.getMessage());
assertThrows(IllegalArgumentException.class, () -> LanguageMetadata.withId("dummy").addVersion(" "),
"Empty versions should not be allowed.");
assertThrows(IllegalArgumentException.class, () -> LanguageMetadata.withId("dummy").addVersion(null),
"Empty versions should not be allowed.");
assertThrows(IllegalArgumentException.class, () -> LanguageMetadata.withId("dummy").addVersion("1.0", ""),
"Empty versions should not be allowed.");
}
@Test
void testVersions() {
LanguageModuleBase lang = makeLanguage(LanguageMetadata.withId("dumdum").name("Name").extensions("o").addDefaultVersion("abc"));
assertThat(lang.getDefaultVersion(), equalTo(lang.getVersion("abc")));
}
@Test
void testMissingVersions() {
Exception e = assertThrows(IllegalStateException.class, () -> makeLanguage(LanguageMetadata.withId("dumdum").name("Name").extensions("o")),
"Languages without versions should not be allowed.");
assertEquals("No versions for 'dumdum'", e.getMessage());
}
@Test
void testNoExtensions() {
Exception ex = assertThrows(IllegalStateException.class, () -> makeLanguage(LanguageMetadata.withId("dumdum").name("Name").addVersion("abc")));
assertThat(ex.getMessage(), containsString("extension"));
}
@Test
void testShortNameDefault() {
LanguageMetadata meta = LanguageMetadata.withId("java").name("Java");
assertEquals("Java", meta.getShortName());
}
@Test
void testInvalidDependency() {
LanguageMetadata meta = LanguageMetadata.withId("java").name("Java");
assertThrows(IllegalArgumentException.class, () -> meta.dependsOnLanguage("not an id"));
}
private static LanguageModuleBase makeLanguage(LanguageMetadata meta) {
return new LanguageModuleBase(meta) {
@Override
public LanguageProcessor createProcessor(LanguagePropertyBundle bundle) {
throw new UnsupportedOperationException("fake instance");
}
};
}
private static void assertInvalidId(String id) {
assertThrows(IllegalArgumentException.class, () -> LanguageMetadata.withId(id));
}
}
| 3,384 | 36.611111 | 151 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/Dummy2LanguageModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang;
import java.util.Objects;
import net.sourceforge.pmd.lang.DummyLanguageModule.Handler;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* A second dummy language used for testing PMD.
*/
public class Dummy2LanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "Dummy2";
public static final String TERSE_NAME = "dummy2";
public Dummy2LanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME).extensions("dummy2")
.addDefaultVersion("1.0"), new Handler());
}
public static Dummy2LanguageModule getInstance() {
return (Dummy2LanguageModule) Objects.requireNonNull(LanguageRegistry.PMD.getLanguageByFullName(NAME));
}
}
| 880 | 28.366667 | 111 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/SemanticErrorReporterTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.contains;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.Logger;
import org.slf4j.event.Level;
import org.slf4j.helpers.NOPLogger;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* Reports errors that occur after parsing. This may be used to implement
* semantic checks in a language specific way.
*/
class SemanticErrorReporterTest {
MessageReporter mockReporter;
Logger mockLogger;
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@BeforeEach
void setup() {
mockReporter = mock(MessageReporter.class);
when(mockReporter.isLoggable(Level.ERROR)).thenReturn(true);
mockLogger = spy(NOPLogger.class);
}
@Test
void testErrorLogging() {
SemanticErrorReporter reporter = SemanticErrorReporter.reportToLogger(mockReporter);
RootNode node = parseMockNode();
assertNull(reporter.getFirstError());
String message = "an error occurred";
reporter.error(node, message);
verify(mockReporter).log(eq(Level.ERROR), contains(message));
verifyNoMoreInteractions(mockLogger);
assertNotNull(reporter.getFirstError());
}
@Test
void testEscaping() {
SemanticErrorReporter reporter = SemanticErrorReporter.reportToLogger(mockReporter);
RootNode node = parseMockNode();
// this is a MessageFormat string
// what ends up being logged is just '
String message = "an apostrophe '' ";
reporter.error(node, message);
// The backend reporter will do its own formatting once again
verify(mockReporter).log(eq(Level.ERROR), contains("an apostrophe ''"));
verifyNoMoreInteractions(mockLogger);
}
private RootNode parseMockNode() {
return helper.parse("(mock (node))", "dummy/file.txt");
}
}
| 2,546 | 30.060976 | 92 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageProcessor;
import net.sourceforge.pmd.lang.LanguageProcessorRegistry;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.impl.AbstractNode;
import net.sourceforge.pmd.lang.ast.impl.GenericNode;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
import net.sourceforge.pmd.lang.document.TextRegion;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
public class DummyNode extends AbstractNode<DummyNode, DummyNode> {
private final boolean findBoundary;
private String xpathName;
private String image;
private final List<Attribute> attributes = new ArrayList<>();
private TextRegion region = TextRegion.caretAt(0);
public DummyNode(String xpathName) {
this(false, xpathName);
}
public DummyNode() {
this(false);
}
public DummyNode(boolean findBoundary) {
this(findBoundary, "dummyNode");
}
public DummyNode(boolean findBoundary, String xpathName) {
this.findBoundary = findBoundary;
this.xpathName = xpathName;
Iterator<Attribute> iter = super.getXPathAttributesIterator();
while (iter.hasNext()) {
attributes.add(iter.next());
}
}
@Override
public void addChild(DummyNode child, int index) {
super.addChild(child, index);
}
@Override
public void setParent(DummyNode node) {
super.setParent(node);
}
public void publicSetChildren(DummyNode... children) {
assert getNumChildren() == 0;
for (int i = children.length - 1; i >= 0; i--) {
addChild(children[i], i);
}
}
@Override
public TextRegion getTextRegion() {
return region;
}
public void setRegion(TextRegion region) {
this.region = region;
}
/**
* Nodes with an image that starts with `#` also set the xpath name.
*/
public void setImage(String image) {
this.image = image;
if (image.startsWith("#")) {
xpathName = image;
}
}
@Override
public String getImage() {
return image;
}
@Override
public String toString() {
return getXPathNodeName() + "[@Image=" + getImage() + "]";
}
@Override
public String getXPathNodeName() {
return xpathName;
}
@Override
public boolean isFindBoundary() {
return findBoundary;
}
public void setXPathAttribute(String name, String value) {
attributes.add(new Attribute(this, name, value));
}
public void clearXPathAttributes() {
attributes.clear();
}
@Override
public Iterator<Attribute> getXPathAttributesIterator() {
return attributes.iterator();
}
public static class DummyRootNode extends DummyNode implements RootNode, GenericNode<DummyNode> {
// FIXME remove this
private static final LanguageProcessor STATIC_PROCESSOR =
DummyLanguageModule.getInstance().createProcessor(DummyLanguageModule.getInstance().newPropertyBundle());
private AstInfo<DummyRootNode> astInfo;
public DummyRootNode() {
TextDocument document = TextDocument.readOnlyString(
"dummy text",
FileId.UNKNOWN,
DummyLanguageModule.getInstance().getDefaultVersion()
);
astInfo = new AstInfo<>(
new ParserTask(
document,
SemanticErrorReporter.noop(),
LanguageProcessorRegistry.singleton(STATIC_PROCESSOR)),
this);
}
public DummyRootNode withTaskInfo(ParserTask task) {
this.astInfo = new AstInfo<>(task, this);
return this;
}
public DummyRootNode withNoPmdComments(Map<Integer, String> suppressMap) {
this.astInfo = astInfo.withSuppressMap(suppressMap);
return this;
}
@Override
public AstInfo<DummyRootNode> getAstInfo() {
return Objects.requireNonNull(astInfo, "no ast info");
}
@Override
public String getXPathNodeName() {
return "dummyRootNode";
}
}
public static class DummyNodeTypeB extends DummyNode {
public DummyNodeTypeB() {
super("dummyNodeB");
}
}
}
| 4,748 | 26.137143 | 117 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNodeWithDeprecatedAttribute.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast;
import java.util.Iterator;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute;
import net.sourceforge.pmd.lang.rule.xpath.impl.AttributeAxisIterator;
/**
* @author Clément Fournier
* @since 6.3.0
*/
public class DummyNodeWithDeprecatedAttribute extends DummyNode {
// this is the deprecated attribute
@Deprecated
public int getSize() {
return 2;
}
// this is a attribute that is deprecated for xpath, because it will be removed.
// it should still be available via Java.
@DeprecatedAttribute(replaceWith = "@Image")
public String getName() {
return "foo";
}
@Override
public Iterator<Attribute> getXPathAttributesIterator() {
return new AttributeAxisIterator(this);
}
}
| 944 | 24.540541 | 84 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNodeWithListAndEnum.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.lang.document.TextRegion;
public class DummyNodeWithListAndEnum extends DummyNode.DummyRootNode {
public DummyNodeWithListAndEnum() {
super();
setRegion(TextRegion.fromOffsetLength(0, 1));
}
public enum MyEnum {
FOO, BAR
}
public MyEnum getEnum() {
return MyEnum.FOO;
}
public List<String> getList() {
return Arrays.asList("A", "B");
}
public List<MyEnum> getEnumList() {
return Arrays.asList(MyEnum.FOO, MyEnum.BAR);
}
public List<String> getEmptyList() {
return Collections.emptyList();
}
public String getSimpleAtt() {
return "foo";
}
}
| 900 | 19.953488 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/BoundaryTraversalTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test for {@link Node} tree traversal methods
*/
class BoundaryTraversalTest {
private DummyNode rootNode;
private DummyNode newDummyNode(boolean boundary) {
return new DummyNode(boundary);
}
private DummyNode addChild(final DummyNode parent, final DummyNode child) {
parent.addChild(child, parent.getNumChildren()); // Append child at the end
return parent;
}
@BeforeEach
void setUpSampleNodeTree() {
rootNode = newDummyNode(false);
}
@Test
void testBoundaryIsHonored() {
addChild(rootNode, addChild(newDummyNode(true), newDummyNode(false)));
List<DummyNode> descendantsOfType = rootNode.descendants(DummyNode.class).toList();
assertEquals(1, descendantsOfType.size());
assertTrue(descendantsOfType.get(0).isFindBoundary());
}
@Test
void testSearchFromBoundary() {
addChild(rootNode, addChild(newDummyNode(true), newDummyNode(false)));
List<DummyNode> descendantsOfType = rootNode.descendants(DummyNode.class).first().descendants(DummyNode.class).toList();
assertEquals(1, descendantsOfType.size());
assertFalse(descendantsOfType.get(0).isFindBoundary());
}
@Test
void testSearchFromBoundaryFromNonOptimisedStream() {
addChild(rootNode, addChild(newDummyNode(true), newDummyNode(false)));
List<DummyNode> descendantsOfType = rootNode.descendants(DummyNode.class).take(1).descendants(DummyNode.class).toList();
assertEquals(1, descendantsOfType.size());
assertFalse(descendantsOfType.get(0).isFindBoundary());
}
@Test
void testSearchIgnoringBoundary() {
addChild(rootNode, addChild(newDummyNode(true), newDummyNode(false)));
List<DummyNode> descendantsOfType = rootNode.findDescendantsOfType(DummyNode.class, true);
assertEquals(2, descendantsOfType.size());
assertTrue(descendantsOfType.get(0).isFindBoundary());
assertFalse(descendantsOfType.get(1).isFindBoundary());
}
}
| 2,456 | 32.202703 | 128 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/impl/DummyTreeUtil.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.impl;
import java.util.List;
import java.util.function.Supplier;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyNodeTypeB;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* @author Clément Fournier
*/
public final class DummyTreeUtil {
private DummyTreeUtil() {
}
public static DummyRootNode root(DummyNode... children) {
return nodeImpl(new DummyRootNode(), children);
}
/** Creates a dummy node with the given children. */
public static DummyNode node(DummyNode... children) {
return nodeImpl(new DummyNode(), children);
}
/** Creates a dummy node with the given children. */
public static DummyNode nodeB(DummyNode... children) {
return nodeImpl(new DummyNodeTypeB(), children);
}
private static <T extends DummyNode> T nodeImpl(T node, DummyNode... children) {
node.publicSetChildren(children);
return node;
}
public static DummyNode followPath(DummyNode root, String path) {
List<Integer> pathIndices = CollectionUtil.map(path.split(""), Integer::valueOf);
Node current = root;
for (int i : pathIndices) {
current = current.getChild(i);
}
return (DummyNode) current;
}
/**
* Must wrap the actual {@link #node(DummyNode...)} usages to assign each node the
* image of its path from the root (in indices). E.g.
*
* <pre>
* node( ""
* node( "0"
* node(), "00"
* node( "01"
* node() "010
* )
* ),
* node() "1"
* )
* </pre>
*/
public static DummyRootNode tree(Supplier<DummyRootNode> supplier) {
DummyRootNode dummyNode = supplier.get();
assignPathImage(dummyNode, "");
return dummyNode;
}
private static void assignPathImage(DummyNode node, String curPath) {
node.setImage(curPath);
for (int i = 0; i < node.getNumChildren(); i++) {
assignPathImage(node.getChild(i), curPath + i);
}
}
/** List of the images of the stream. */
public static List<String> pathsOf(NodeStream<?> stream) {
return stream.toList(Node::getImage);
}
}
| 2,555 | 25.350515 | 89 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/impl/AbstractNodeTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.impl;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.node;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.root;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.tree;
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.fail;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.Node;
/**
* Unit test for {@link AbstractNode}.
*/
class AbstractNodeTest {
private static final int NUM_CHILDREN = 3;
private static final int NUM_GRAND_CHILDREN = 3;
// Note that in order to successfully run JUnitParams, we need to explicitly use `Integer` instead of `int`
static Integer[] childrenIndexes() {
return getIntRange(NUM_CHILDREN);
}
static Integer[] grandChildrenIndexes() {
return getIntRange(NUM_GRAND_CHILDREN);
}
private static Integer[] getIntRange(final int exclusiveLimit) {
final Integer[] childIndexes = new Integer[exclusiveLimit];
for (int i = 0; i < exclusiveLimit; i++) {
childIndexes[i] = i;
}
return childIndexes;
}
static Object childrenAndGrandChildrenIndexes() {
final Integer[] childrenIndexes = childrenIndexes();
final Integer[] grandChildrenIndexes = grandChildrenIndexes();
final Object[] indexes = new Object[childrenIndexes.length * grandChildrenIndexes.length];
int i = 0;
for (final int childIndex : childrenIndexes) {
for (final int grandChildIndex : grandChildrenIndexes) {
indexes[i++] = new Integer[] { childIndex, grandChildIndex };
}
}
return indexes;
}
private DummyRootNode rootNode;
@BeforeEach
void setUpSampleNodeTree() {
rootNode = tree(
() -> {
DummyRootNode root = root();
for (int i = 0; i < NUM_CHILDREN; i++) {
final DummyNode child = node();
for (int j = 0; j < NUM_GRAND_CHILDREN; j++) {
child.addChild(node(), j);
}
root.addChild(child, i);
}
return root;
}
);
}
/**
* Explicitly tests the {@code remove} method, and implicitly the {@code removeChildAtIndex} method
*/
@ParameterizedTest
@MethodSource("childrenIndexes")
void testRemoveChildOfRootNode(final int childIndex) {
final DummyNode child = rootNode.getChild(childIndex);
final List<? extends DummyNode> grandChildren = child.children().toList();
// Do the actual removal
child.remove();
// Check that conditions have been successfully changed
assertEquals(NUM_CHILDREN - 1, rootNode.getNumChildren());
assertNull(child.getParent());
// The child node is expected to still have all its children and vice versa
assertEquals(NUM_GRAND_CHILDREN, child.getNumChildren());
for (final Node grandChild : grandChildren) {
assertEquals(child, grandChild.getParent());
}
}
@Test
void testPrevNextSiblings() {
DummyRootNode root = tree(() -> root(node(), node()));
assertNull(root.getNextSibling());
assertNull(root.getPreviousSibling());
DummyNode c0 = root.getChild(0);
DummyNode c1 = root.getChild(1);
assertSame(c0, c1.getPreviousSibling());
assertSame(c1, c0.getNextSibling());
assertNull(c1.getNextSibling());
assertNull(c0.getPreviousSibling());
}
/**
* Explicitly tests the {@code remove} method, and implicitly the {@code removeChildAtIndex} method.
* This is a border case as the root node does not have any parent.
*/
@Test
void testRemoveRootNode() {
// Check that the root node has the expected properties
final List<? extends DummyNode> children = rootNode.children().toList();
// Do the actual removal
rootNode.remove();
// Check that conditions have been successfully changed, i.e.,
// the root node is expected to still have all its children and vice versa
assertEquals(NUM_CHILDREN, rootNode.getNumChildren());
assertNull(rootNode.getParent());
for (final Node aChild : children) {
assertEquals(rootNode, aChild.getParent());
}
}
/**
* Explicitly tests the {@code remove} method, and implicitly the {@code removeChildAtIndex} method.
* These are border cases as grandchildren nodes do not have any child.
*/
@ParameterizedTest
@MethodSource("childrenAndGrandChildrenIndexes")
void testRemoveGrandChildNode(final int childIndex, final int grandChildIndex) {
final DummyNode child = rootNode.getChild(childIndex);
final DummyNode grandChild = child.getChild(grandChildIndex);
// Do the actual removal
grandChild.remove();
// Check that conditions have been successfully changed
assertEquals(NUM_GRAND_CHILDREN - 1, child.getNumChildren());
assertEquals(0, grandChild.getNumChildren());
assertNull(grandChild.getParent());
}
/**
* Explicitly tests the {@code removeChildAtIndex} method.
*/
@ParameterizedTest
@MethodSource("childrenIndexes")
void testRemoveRootNodeChildAtIndex(final int childIndex) {
final List<? extends DummyNode> originalChildren = rootNode.children().toList();
// Do the actual removal
rootNode.removeChildAtIndex(childIndex);
// Check that conditions have been successfully changed
assertEquals(NUM_CHILDREN - 1, rootNode.getNumChildren());
int j = 0;
for (int i = 0; i < rootNode.getNumChildren(); i++) {
if (j == childIndex) { // Skip the removed child
j++;
}
// Check that the nodes have been rightly shifted
assertEquals(originalChildren.get(j), rootNode.getChild(i));
// Check that the child index has been updated
assertEquals(i, rootNode.getChild(i).getIndexInParent());
j++;
}
}
/**
* Explicitly tests the {@code removeChildAtIndex} method.
* Test that invalid indexes cases are handled without exception.
*/
@Test
void testRemoveChildAtIndexWithInvalidIndex() {
try {
rootNode.removeChildAtIndex(-1);
rootNode.removeChildAtIndex(rootNode.getNumChildren());
} catch (final Exception e) {
fail("No exception was expected.");
}
}
/**
* Explicitly tests the {@code removeChildAtIndex} method.
* This is a border case as the method invocation should do nothing.
*/
@ParameterizedTest
@MethodSource("grandChildrenIndexes")
void testRemoveChildAtIndexOnNodeWithNoChildren(final int grandChildIndex) {
// grandChild does not have any child
final DummyNode grandChild = rootNode.getChild(grandChildIndex).getChild(grandChildIndex);
// Do the actual removal
grandChild.removeChildAtIndex(0);
// If here, no exception has been thrown
// Check that this node still does not have any children
assertEquals(0, grandChild.getNumChildren());
}
}
| 7,878 | 34.490991 | 111 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/impl/javacc/JavaEscapeReaderTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.impl.javacc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.document.TextDocument;
class JavaEscapeReaderTest {
TextDocument readString(String input) {
TextDocument intext = TextDocument.readOnlyString(Chars.wrap(input), DummyLanguageModule.getInstance().getDefaultVersion());
return new JavaEscapeTranslator(intext).translateDocument();
}
@Test
void testSimpleRead() throws IOException {
String input = "abcdede";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap(input), r.getText());
}
}
@Test
void testNotAnEscape1Read() throws IOException {
String input = "abc\\dede";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap(input), r.getText());
}
}
@Test
void testNotAnEscape1Read2() throws IOException {
String input = "abc\\\\\\dede";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap(input), r.getText());
}
}
@Test
void testAnEscapeStopAtEnd() throws IOException {
String input = "abc\\\\\\u00a0dede";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap("abc\u00a0dede"), r.getText());
}
}
@Test
void testSeveralEscapes() throws IOException {
String input = "abc\\\\\\u00a0d\\uu00a0ede";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap("abc\u00a0d\u00a0ede"), r.getText());
}
}
@Test
void testAnEscapeInsideBlock() throws IOException {
String input = "abc\\\\\\u00a0dede\\u00a0";
try (TextDocument r = readString(input)) {
assertEquals(Chars.wrap("abc\u00a0dede\u00a0"), r.getText());
}
}
}
| 2,148 | 25.8625 | 132 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/impl/javacc/CharStreamTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.impl.javacc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.EOFException;
import java.io.IOException;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.document.TextDocument;
class CharStreamTest {
private LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
@Test
void testReadZeroChars() throws IOException {
CharStream stream = simpleCharStream("");
assertThrows(EOFException.class, stream::readChar);
assertEquals(stream.getStartOffset(), 0);
assertEquals(stream.getEndOffset(), 0);
}
@Test
void testMultipleEofReads() throws IOException {
CharStream stream = simpleCharStream("");
for (int i = 0; i < 3; i++) {
assertThrows(EOFException.class, stream::readChar);
}
}
@Test
void testReadStuff() throws IOException {
CharStream stream = simpleCharStream("abcd");
assertEquals('a', stream.readChar());
assertEquals('b', stream.readChar());
assertEquals('c', stream.readChar());
assertEquals('d', stream.readChar());
assertThrows(EOFException.class, stream::readChar);
}
@Test
void testReadBacktrack() throws IOException {
CharStream stream = simpleCharStream("abcd");
assertEquals('a', stream.markTokenStart());
assertEquals('b', stream.readChar());
assertEquals('c', stream.readChar());
assertEquals('d', stream.readChar());
assertEquals("abcd", stream.getTokenImage());
stream.backup(2);
assertEquals('c', stream.readChar());
assertEquals('d', stream.readChar());
assertThrows(EOFException.class, stream::readChar);
}
@Test
void testReadBacktrackWithEscapes() throws IOException {
CharStream stream = javaCharStream("__\\u00a0_\\u00a0_");
assertEquals('_', stream.markTokenStart());
assertEquals('_', stream.readChar());
assertEquals('\u00a0', stream.readChar());
assertEquals('_', stream.readChar());
assertEquals("__\u00a0_", stream.getTokenImage());
stream.backup(2);
assertEquals('\u00a0', stream.readChar());
assertEquals('_', stream.readChar());
assertEquals('\u00a0', stream.readChar());
assertEquals("__\u00a0_\u00a0", stream.getTokenImage());
assertEquals('_', stream.readChar());
stream.backup(2);
assertEquals('\u00a0', stream.markTokenStart());
assertEquals('_', stream.readChar());
assertEquals("\u00a0_", stream.getTokenImage());
assertThrows(EOFException.class, stream::readChar);
}
@Test
void testBacktrackTooMuch() throws IOException {
CharStream stream = simpleCharStream("abcd");
assertEquals('a', stream.readChar());
assertEquals('b', stream.readChar());
assertEquals('c', stream.markTokenStart());
assertEquals('d', stream.readChar());
stream.backup(2); // ok
assertThrows(IllegalArgumentException.class, () -> stream.backup(1));
}
@Test
void testBacktrackTooMuch2() throws IOException {
CharStream stream = simpleCharStream("abcd");
assertEquals('a', stream.markTokenStart());
assertEquals('b', stream.readChar());
assertEquals('c', stream.readChar());
assertEquals('d', stream.readChar());
assertThrows(IllegalArgumentException.class, () -> stream.backup(10));
}
CharStream simpleCharStream(String abcd) {
return CharStream.create(TextDocument.readOnlyString(abcd, dummyVersion), TokenDocumentBehavior.DEFAULT);
}
CharStream javaCharStream(String abcd) {
return CharStream.create(
TextDocument.readOnlyString(abcd, dummyVersion),
new TokenDocumentBehavior(Collections.emptyList()) {
@Override
public TextDocument translate(TextDocument text) throws MalformedSourceException {
return new JavaEscapeTranslator(text).translateDocument();
}
});
}
}
| 4,566 | 28.849673 | 113 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/internal/NodeStreamBlanketTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.internal;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.node;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.nodeB;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.root;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyNodeTypeB;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
/**
* Asserts invariants independent of the NodeStream implementation. Error
* messages are not great but coverage is.
*/
class NodeStreamBlanketTest<T extends Node> {
private static final List<Node> ASTS = Arrays.asList(
tree(
() ->
root(
node(
node(),
nodeB(
node(
nodeB()
)
),
node(),
nodeB()
),
node()
)
),
tree(
() ->
root(
node(),
node(),
nodeB(
node()
),
node()
)
)
);
@ParameterizedTest
@MethodSource("primeNumbers")
void testToListConsistency(NodeStream<T> stream) {
List<T> toList = stream.toList();
List<T> collected = stream.collect(Collectors.toList());
List<T> fromStream = stream.toStream().collect(Collectors.toList());
List<T> cached = stream.cached().toList();
assertEquals(toList, collected);
assertEquals(toList, fromStream);
assertEquals(toList, cached);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testToListSize(NodeStream<T> stream) {
List<T> toList = stream.toList();
assertEquals(toList.size(), stream.count());
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testLast(NodeStream<T> stream) {
assertImplication(
stream,
prop("nonEmpty", NodeStream::nonEmpty),
prop("last() == toList().last()", it -> it.last() == it.toList().get(it.count() - 1))
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testFirst(NodeStream<T> stream) {
assertImplication(
stream,
prop("nonEmpty", NodeStream::nonEmpty),
prop("first() == toList().get(0)", it -> it.first() == it.toList().get(0))
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testDrop(NodeStream<T> stream) {
assertImplication(
stream,
prop("nonEmpty", NodeStream::nonEmpty),
prop("drop(0) == this", it -> it.drop(0) == it),
prop("drop(1).count() == count() - 1", it -> it.drop(1).count() == it.count() - 1),
prop("drop(1).toList() == toList().tail()", it -> it.drop(1).toList().equals(tail(it.toList())))
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testDropLast(NodeStream<T> stream) {
assertImplication(
stream,
prop("nonEmpty", NodeStream::nonEmpty),
prop("dropLast(0) == this", it -> it.dropLast(0) == it),
prop("dropLast(1).count() == count() - 1", it -> it.dropLast(1).count() == it.count() - 1),
prop("dropLast(1).toList() == toList().init()", it -> it.dropLast(1).toList().equals(init(it.toList())))
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testDropMoreThan1(NodeStream<T> stream) {
assertImplication(
stream,
prop("count() > 1", it -> it.count() > 1),
prop("drop(2).toList() == toList().tail().tail()", it -> it.drop(2).toList().equals(tail(tail(it.toList())))),
prop("drop(1).drop(1) == drop(2)", it -> it.drop(1).drop(1).toList().equals(it.drop(2).toList()))
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testTake(NodeStream<T> stream) {
assertImplication(
stream,
prop("nonEmpty", NodeStream::nonEmpty),
prop("it.take(0).count() == 0", it -> it.take(0).count() == 0),
prop("it.take(1).count() == 1", it -> it.take(1).count() == 1),
prop("it.take(it.count()).count() == it.count()", it -> it.take(it.count()).count() == it.count())
);
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testGet(NodeStream<T> stream) {
for (int i = 0; i < 100; i++) {
assertSame(stream.get(i), stream.drop(i).first(), "stream.get(i) == stream.drop(i).first()");
}
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testGetNegative(NodeStream<T> stream) {
assertThrows(IllegalArgumentException.class, () -> stream.get(-1));
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testDropNegative(NodeStream<T> stream) {
assertThrows(IllegalArgumentException.class, () -> stream.drop(-1));
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testTakeNegative(NodeStream<T> stream) {
assertThrows(IllegalArgumentException.class, () -> stream.take(-1));
}
@ParameterizedTest
@MethodSource("primeNumbers")
void testEmpty(NodeStream<T> stream) {
assertEquivalence(
stream,
prop("isEmpty", NodeStream::isEmpty),
prop("!nonEmpty", it -> !it.nonEmpty()),
prop("last() == null", it -> it.last() == null),
prop("first() == null", it -> it.first() == null),
prop("first(_ -> true) == null", it -> it.first(i -> true) == null),
prop("first(Node.class) == null", it -> it.first(Node.class) == null),
prop("count() == 0", it -> it.count() == 0),
prop("any(_) == false", it -> !it.any(i -> true)),
prop("all(_) == true", it -> it.all(i -> false)),
prop("none(_) == true", it -> it.none(i -> true))
);
}
static Collection<?> primeNumbers() {
return ASTS.stream().flatMap(
root -> Stream.of(
root.asStream(),
root.children().first().asStream(),
NodeStream.empty()
)
).flatMap(
// add some transformations on each of them
stream -> Stream.of(
stream,
stream.drop(1),
stream.take(2),
stream.filter(n -> !n.getImage().isEmpty()),
stream.firstChild(DummyNodeTypeB.class),
stream.children(DummyNodeTypeB.class),
stream.descendants(DummyNodeTypeB.class),
stream.ancestors(DummyNodeTypeB.class),
stream.descendants(),
stream.ancestors(),
stream.ancestorsOrSelf(),
stream.followingSiblings(),
stream.precedingSiblings(),
stream.descendantsOrSelf(),
stream.children(),
stream.children().filter(c -> c.getImage().equals("0")),
stream.children(DummyNode.class)
)
).flatMap(
// add some transformations on each of them
stream -> Stream.of(
stream,
stream.filterIs(DummyNode.class),
stream.take(1),
stream.drop(1),
stream.filter(n -> !n.getImage().isEmpty()),
stream.cached()
)
).collect(Collectors.toCollection(ArrayList::new));
}
@SafeVarargs
private static <T> void assertEquivalence(T input, Prop<? super T>... properties) {
for (Prop<? super T> prop1 : properties) {
for (Prop<? super T> prop2 : properties) {
boolean p1 = prop1.test(input);
assertEquals(
p1, prop2.test(input),
"Expected (" + prop1.description + ") === (" + prop2.description
+ "), but the LHS was " + p1 + " and the RHS was " + !p1
);
}
}
}
@SafeVarargs
private static <T> void assertImplication(T input, Prop<? super T> precond, Prop<? super T>... properties) {
assumeTrue(precond.test(input));
for (Prop<? super T> prop2 : properties) {
assertTrue(
prop2.test(input),
"Expected (" + precond.description + ") to entail (" + prop2.description
+ "), but the latter was false"
);
}
}
static <T> Prop<T> prop(String desc, Predicate<? super T> pred) {
return new Prop<>(pred, desc);
}
static <T> List<T> tail(List<T> ts) {
return ts.subList(1, ts.size());
}
static <T> List<T> init(List<T> ts) {
return ts.subList(0, ts.size() - 1);
}
static class Prop<T> {
final Predicate<? super T> property;
final String description;
Prop(Predicate<? super T> property, String description) {
this.property = property;
this.description = description;
}
boolean test(T t) {
return property.test(t);
}
}
}
| 10,228 | 32.983389 | 122 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/internal/NodeStreamTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ast.internal;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.followPath;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.node;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.nodeB;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.pathsOf;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.root;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.tree;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
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.util.Arrays;
import java.util.Optional;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyNodeTypeB;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.ast.NodeStream.DescendantNodeStream;
/**
* @author Clément Fournier
*/
class NodeStreamTest {
private final DummyNode tree1 = tree(
() ->
root(// ""
nodeB(// 0
node(), // 00
nodeB(// 01
node(), // 010
node(// 011
node() // 0110
),
node(), // 012
node() // 013
)
),
node() // 1
)
);
private final DummyNode tree2 = tree(
() ->
root(
node(),
node(),
node(
node()
),
node()
)
);
@Test
void testStreamConstructionIsNullSafe() {
assertTrue(NodeStream.of((Node) null).isEmpty());
assertThat(NodeStream.of(null, null, tree1).count(), equalTo(1));
assertThat(NodeStream.fromIterable(Arrays.asList(tree1, null, null)).count(), equalTo(1));
assertThat(NodeStream.ofOptional(Optional.empty()).count(), equalTo(0));
}
@Test
void testMapIsNullSafe() {
assertTrue(tree1.descendantsOrSelf().map(n -> null).isEmpty());
}
@Test
void testFlatMapIsNullSafe() {
assertTrue(tree1.descendantsOrSelf().flatMap(n -> null).isEmpty());
}
@Test
void testChildrenStream() {
assertThat(pathsOf(tree1.children()), contains("0", "1"));
assertThat(pathsOf(tree1.asStream().children()), contains("0", "1"));
}
@Test
void testChildrenEagerEvaluation() {
NodeStream<? extends Node> children = tree1.children();
assertThat(children, is(instanceOf(AxisStream.ChildrenStream.class)));
NodeStream<Node> children1 = children.children();
assertEquals(GreedyNStream.GreedyKnownNStream.class, children1.getClass());
assertEquals(SingletonNodeStream.class, children1.filter(it -> it.getImage().endsWith("1")).getClass());
}
@Test
void testDescendantStream() {
assertThat(pathsOf(tree1.descendants()), contains("0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(tree1.asStream().descendants()), contains("0", "00", "01", "010", "011", "0110", "012", "013", "1"));
}
@Test
void testSingletonStream() {
assertThat(pathsOf(tree1.asStream()), contains(""));
assertThat(pathsOf(NodeStream.of(tree1)), contains(""));
}
@Test
void testDescendantOrSelfStream() {
assertThat(pathsOf(tree1.descendantsOrSelf()), contains("", "0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(NodeStream.of(tree1).descendantsOrSelf()), contains("", "0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(followPath(tree1, "0110").descendantsOrSelf()), contains("0110")); // with a leaf node
}
@Test
void testAncestors() {
// 010
Node node = tree1.children().children().children().first();
assertEquals("010", node.getImage());
assertThat(pathsOf(node.ancestors()), contains("01", "0", ""));
assertThat(pathsOf(node.ancestorsOrSelf()), contains("010", "01", "0", ""));
assertEquals("01", node.getNthParent(1).getImage());
assertEquals("0", node.getNthParent(2).getImage());
assertEquals("", node.getNthParent(3).getImage());
assertNull(node.getNthParent(4));
}
@Test
void testAncestorsFiltered() {
// 0110
Node node = tree1.children().children().children().children().first();
assertEquals("0110", node.getImage());
assertThat(pathsOf(node.ancestors(DummyNodeTypeB.class)), contains("01", "0"));
assertThat(pathsOf(node.ancestorsOrSelf().filterIs(DummyNodeTypeB.class)), contains("01", "0"));
}
@Test
void testAncestorsFilteredDrop() {
// 0110
Node node = tree1.children().children().children().children().first();
assertEquals("0110", node.getImage());
assertThat(pathsOf(node.ancestors(DummyNodeTypeB.class).drop(1)), contains("0"));
assertThat(pathsOf(node.ancestorsOrSelf().filterIs(DummyNodeTypeB.class).drop(1)), contains("0"));
}
@Test
void testFollowingSiblings() {
assertThat(pathsOf(followPath(tree2, "2").asStream().followingSiblings()), contains("3"));
assertThat(pathsOf(followPath(tree2, "0").asStream().followingSiblings()), contains("1", "2", "3"));
assertTrue(pathsOf(followPath(tree2, "3").asStream().followingSiblings()).isEmpty());
}
@Test
void testPrecedingSiblings() {
assertThat(pathsOf(followPath(tree2, "2").asStream().precedingSiblings()), contains("0", "1"));
assertThat(pathsOf(followPath(tree2, "3").asStream().precedingSiblings()), contains("0", "1", "2"));
assertTrue(pathsOf(followPath(tree2, "0").asStream().precedingSiblings()).isEmpty());
}
@Test
void testRootSiblings() {
assertTrue(tree2.asStream().precedingSiblings().isEmpty());
assertTrue(tree2.asStream().followingSiblings().isEmpty());
}
@Test
void testAncestorStream() {
assertThat(pathsOf(followPath(tree1, "01").ancestors()), contains("0", ""));
assertThat(pathsOf(followPath(tree1, "01").asStream().ancestors()), contains("0", ""));
}
@Test
void testParentStream() {
assertThat(pathsOf(followPath(tree1, "01").asStream().parents()), contains("0"));
}
@Test
void testAncestorStreamUnion() {
assertThat(pathsOf(NodeStream.union(followPath(tree1, "01").ancestors(),
tree2.children().ancestors())), contains("0", "", "", "", "", ""));
}
@Test
void testDistinct() {
assertThat(pathsOf(NodeStream.union(followPath(tree1, "01").ancestors(),
tree2.children().ancestors()).distinct()), contains("0", "", "")); // roots of both trees
}
@Test
void testGet() {
// ("0", "00", "01", "010", "011", "0110", "012", "013", "1")
DescendantNodeStream<DummyNode> stream = tree1.descendants();
assertEquals("0", stream.get(0).getImage());
assertEquals("00", stream.get(1).getImage());
assertEquals("010", stream.get(3).getImage());
assertEquals("011", stream.get(4).getImage());
assertEquals("0110", stream.get(5).getImage());
assertNull(stream.get(9));
}
@Test
void testNodeStreamsCanBeIteratedSeveralTimes() {
DescendantNodeStream<DummyNode> stream = tree1.descendants();
assertThat(stream.count(), equalTo(9));
assertThat(stream.count(), equalTo(9));
assertThat(pathsOf(stream), contains("0", "00", "01", "010", "011", "0110", "012", "013", "1"));
assertThat(pathsOf(stream.filter(n -> n.getNumChildren() == 0)),
contains("00", "010", "0110", "012", "013", "1"));
}
@Test
void testNodeStreamPipelineIsLazy() {
MutableInt numEvals = new MutableInt();
tree1.descendants().filter(n -> {
numEvals.increment();
return true;
});
assertThat(numEvals.getValue(), equalTo(0));
}
@Test
void testForkJoinUpstreamPipelineIsExecutedAtMostOnce() {
MutableInt numEvals = new MutableInt();
NodeStream<Node> stream =
NodeStream
.forkJoin(
hook(numEvals::increment, tree1.descendants()),
n -> NodeStream.of(n).filter(m -> m.hasImageEqualTo("0")),
n -> NodeStream.of(n).filter(m -> m.hasImageEqualTo("1"))
);
// assertThat(numEvals.getValue(), equalTo(0)); // not evaluated yet
assertThat(stream.count(), equalTo(2));
assertThat(numEvals.getValue(), equalTo(9)); // evaluated *once* every element of the upper stream
assertThat(stream.count(), equalTo(2));
assertThat(numEvals.getValue(), equalTo(9)); // not reevaluated
}
@Test
void testCachedStreamUpstreamPipelineIsExecutedAtMostOnce() {
MutableInt upstreamEvals = new MutableInt();
MutableInt downstreamEvals = new MutableInt();
NodeStream<DummyNode> stream =
tree1.descendants()
.filter(n -> n.getImage().matches("0.*"))
.take(4)
.peek(n -> upstreamEvals.increment())
.cached()
.filter(n -> true)
.peek(n -> downstreamEvals.increment());
// assertThat(upstreamEvals.getValue(), equalTo(0)); // not evaluated yet
assertThat(stream.count(), equalTo(4));
assertThat(upstreamEvals.getValue(), equalTo(4)); // evaluated once
assertThat(downstreamEvals.getValue(), equalTo(4)); // evaluated once
assertThat(stream.count(), equalTo(4));
assertThat(upstreamEvals.getValue(), equalTo(4)); // upstream was not reevaluated
assertThat(downstreamEvals.getValue(), equalTo(4)); // downstream was not reevaluated
}
@Test
void testUnionIsLazy() {
MutableInt tree1Evals = new MutableInt();
MutableInt tree2Evals = new MutableInt();
NodeStream<Node> unionStream = NodeStream.union(tree1.descendantsOrSelf().peek(n -> tree1Evals.increment()),
tree2.descendantsOrSelf().peek(n -> tree2Evals.increment()));
assertThat(tree1Evals.getValue(), equalTo(0)); // not evaluated yet
assertThat(tree2Evals.getValue(), equalTo(0)); // not evaluated yet
assertSame(unionStream.first(), tree1);
assertThat(tree1Evals.getValue(), equalTo(1)); // evaluated once
assertThat(tree2Evals.getValue(), equalTo(0)); // not evaluated
}
@Test
void testSomeOperationsAreLazy() {
MutableInt tree1Evals = new MutableInt();
NodeStream<DummyNode> unionStream = tree1.descendantsOrSelf().peek(n -> tree1Evals.increment());
int i = 0;
assertThat(tree1Evals.getValue(), equalTo(i)); // not evaluated yet
unionStream.first();
assertThat(tree1Evals.getValue(), equalTo(++i)); // evaluated once
unionStream.nonEmpty();
assertThat(tree1Evals.getValue(), equalTo(i)); // not evaluated, because of optimised implementation
unionStream.isEmpty();
assertThat(tree1Evals.getValue(), equalTo(i)); // not evaluated, because of optimised implementation
// those don't trigger any evaluation
unionStream.map(p -> p);
unionStream.filter(p -> true);
unionStream.append(tree2.descendantsOrSelf());
unionStream.prepend(tree2.descendantsOrSelf());
unionStream.flatMap(Node::descendantsOrSelf);
unionStream.iterator();
// unionStream.cached();
unionStream.descendants();
unionStream.ancestors();
unionStream.followingSiblings();
unionStream.precedingSiblings();
unionStream.children();
unionStream.distinct();
unionStream.take(4);
unionStream.drop(4);
assertThat(tree1Evals.getValue(), equalTo(i)); // not evaluated
}
@Test
void testFollowingSiblingsNonEmpty() {
DummyNode node = followPath(tree1, "012");
NodeStream<Node> nodes = node.asStream().followingSiblings();
assertTrue(nodes instanceof SingletonNodeStream);
assertEquals("013", nodes.first().getImage());
}
@Test
void testPrecedingSiblingsNonEmpty() {
DummyNode node = followPath(tree1, "011");
NodeStream<Node> nodes = node.asStream().precedingSiblings();
assertTrue(nodes instanceof SingletonNodeStream);
assertEquals("010", nodes.first().getImage());
}
@Test
void testPrecedingSiblingsDrop() {
DummyNode node = followPath(tree1, "012");
NodeStream<Node> nodes = node.asStream().precedingSiblings().drop(1);
assertThat(pathsOf(nodes), contains("011"));
}
@Test
void testFollowingSiblingsDrop() {
DummyNode node = followPath(tree1, "011");
NodeStream<Node> nodes = node.asStream().followingSiblings().drop(1);
assertThat(pathsOf(nodes), contains("013"));
}
private static <T extends Node> NodeStream<T> hook(Runnable hook, NodeStream<T> stream) {
return stream.filter(t -> {
hook.run();
return true;
});
}
}
| 14,162 | 32.964029 | 142 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/metrics/ParameterizedMetricKeyTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.metrics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
class ParameterizedMetricKeyTest {
private static final MetricOptions DUMMY_VERSION_1 = MetricOptions.ofOptions(Options.DUMMY1, Options.DUMMY2);
private static final MetricOptions DUMMY_VERSION_2 = MetricOptions.ofOptions(Options.DUMMY2);
private static final Metric<Node, Double> DUMMY_METRIC = Metric.of((n, opts) -> 0., t -> t, "dummy");
@Test
void testIdentity() {
ParameterizedMetricKey<Node, ?> key1 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
ParameterizedMetricKey<Node, ?> key2 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
assertEquals(key1, key2);
assertSame(key1, key2);
}
@Test
void testVersioning() {
ParameterizedMetricKey<Node, ?> key1 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
ParameterizedMetricKey<Node, ?> key2 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_2);
assertNotEquals(key1, key2);
assertNotSame(key1, key2);
}
@Test
void testToString() {
ParameterizedMetricKey<Node, ?> key1 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
assertTrue(key1.toString().contains(key1.metric.displayName()));
assertTrue(key1.toString().contains(key1.options.toString()));
}
@Test
void testAdHocMetricKey() {
ParameterizedMetricKey<Node, ?> key1 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
ParameterizedMetricKey<Node, ?> key2 = ParameterizedMetricKey.getInstance(DUMMY_METRIC, DUMMY_VERSION_1);
assertNotNull(key1);
assertNotNull(key2);
assertSame(key1, key2);
assertEquals(key1, key2);
assertTrue(key1.toString().contains(key1.metric.displayName()));
assertTrue(key1.toString().contains(key1.options.toString()));
}
private enum Options implements MetricOption {
DUMMY1,
DUMMY2;
@Override
public String valueName() {
return null;
}
}
}
| 2,654 | 31.777778 | 113 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextRegionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TextRegionTest {
@Test
void testIsEmpty() {
TextRegion r = TextRegion.fromOffsetLength(0, 0);
assertTrue(r.isEmpty());
}
@Test
void testEmptyContains() {
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
assertFalse(r1.contains(0));
}
@Test
void testContains() {
TextRegion r1 = TextRegion.fromOffsetLength(1, 2);
assertFalse(r1.contains(0));
assertTrue(r1.contains(1));
assertTrue(r1.contains(2));
assertFalse(r1.contains(3));
}
@Test
void testIntersectZeroLen() {
// r1: [[-----
// r2: [ -----[
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
TextRegion r2 = TextRegion.fromOffsetLength(0, 5);
TextRegion inter = doIntersect(r1, r2);
assertEquals(r1, inter);
}
@Test
void testIntersectZeroLen2() {
// r1: -----[[
// r2: [-----[
TextRegion r1 = TextRegion.fromOffsetLength(5, 0);
TextRegion r2 = TextRegion.fromOffsetLength(0, 5);
TextRegion inter = doIntersect(r1, r2);
assertEquals(r1, inter);
}
@Test
void testIntersectZeroLen3() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(3, 3);
TextRegion r2 = TextRegion.fromOffsetLength(2, 1);
TextRegion inter = doIntersect(r1, r2);
assertRegionEquals(inter, 3, 0);
assertTrue(inter.isEmpty());
}
@Test
void testIntersectZeroLen4() {
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
TextRegion inter = doIntersect(r1, r1);
assertEquals(r1, inter);
}
@Test
void testNonEmptyIntersect() {
// r1: ---[-- --[
// r2: [--- --[--
// i: ---[--[--
TextRegion r1 = TextRegion.fromOffsetLength(3, 4);
TextRegion r2 = TextRegion.fromOffsetLength(0, 5);
TextRegion inter = doIntersect(r1, r2);
assertRegionEquals(inter, 3, 2);
}
@Test
void testIntersectContained() {
// r1: --[- - ---[
// r2: -- -[-[---
// i: -- -[-[---
TextRegion r1 = TextRegion.fromOffsetLength(2, 5);
TextRegion r2 = TextRegion.fromOffsetLength(3, 1);
TextRegion inter = doIntersect(r1, r2);
assertRegionEquals(inter, 3, 1);
}
@Test
void testIntersectDisjoint() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(4, 3);
TextRegion r2 = TextRegion.fromOffsetLength(2, 1);
noIntersect(r1, r2);
}
@Test
void testOverlapContained() {
// r1: --[- - ---[
// r2: -- -[-[---
// i: -- -[-[---
TextRegion r1 = TextRegion.fromOffsetLength(2, 5);
TextRegion r2 = TextRegion.fromOffsetLength(3, 1);
assertOverlap(r1, r2);
}
@Test
void testOverlapDisjoint() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(4, 3);
TextRegion r2 = TextRegion.fromOffsetLength(2, 1);
assertNoOverlap(r1, r2);
}
@Test
void testOverlapBoundary() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(3, 3);
TextRegion r2 = TextRegion.fromOffsetLength(2, 1);
assertNoOverlap(r1, r2);
}
@Test
void testCompare() {
// r1: --[-[---
// r2: -- -[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = TextRegion.fromOffsetLength(3, 3);
assertIsBefore(r1, r2);
}
@Test
void testCompareSameOffset() {
// r1: [-[--
// r2: [- --[
TextRegion r1 = TextRegion.fromOffsetLength(0, 1);
TextRegion r2 = TextRegion.fromOffsetLength(0, 3);
assertIsBefore(r1, r2);
}
@Test
void testUnion() {
// r1: --[-[---
// r2: -- -[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = TextRegion.fromOffsetLength(3, 3);
TextRegion union = doUnion(r1, r2);
assertRegionEquals(union, 2, 4);
}
@Test
void testUnionDisjoint() {
// r1: --[-[- ---
// r2: -- ---[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = TextRegion.fromOffsetLength(5, 3);
TextRegion union = doUnion(r1, r2);
assertRegionEquals(union, 2, 6);
}
@Test
void testGrowLeft() {
// r1: --[-[-
// r2: [-- -[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = r1.growLeft(+2);
assertRegionEquals(r2, 0, 3);
}
@Test
void testGrowLeftNegative() {
// r1: --[- [-
// r2: -- -[[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = r1.growLeft(-1);
assertRegionEquals(r2, 3, 0);
}
@Test
void testGrowLeftOutOfBounds() {
// r1: --[-[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
assertThrows(AssertionError.class, () -> r1.growLeft(4));
}
@Test
void testGrowRight() {
// r1: --[-[-
// r2: --[- -[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = r1.growRight(+1);
assertRegionEquals(r2, 2, 2);
}
@Test
void testGrowRightNegative() {
// r1: --[ -[-
// r2: --[[- -
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
TextRegion r2 = r1.growRight(-1);
assertRegionEquals(r2, 2, 0);
}
@Test
void testGrowRightOutOfBounds() {
// r1: --[-[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
assertThrows(AssertionError.class, () -> r1.growRight(-2));
}
private static void assertRegionEquals(TextRegion region, int start, int len) {
assertEquals(start, region.getStartOffset(), "Start offset");
assertEquals(len, region.getLength(), "Length");
}
private static void assertIsBefore(TextRegion r1, TextRegion r2) {
assertTrue(r1.compareTo(r2) < 0, "Region " + r1 + " should be before " + r2);
assertTrue(r2.compareTo(r1) > 0, "Region " + r2 + " should be after " + r1);
}
private static void assertNoOverlap(TextRegion r1, TextRegion r2) {
assertFalse(r1.overlaps(r2), "Regions " + r1 + " and " + r2 + " should not overlap");
}
private static void assertOverlap(TextRegion r1, TextRegion r2) {
assertTrue(r1.overlaps(r2), "Regions " + r1 + " and " + r2 + " should overlap");
}
private TextRegion doIntersect(TextRegion r1, TextRegion r2) {
TextRegion inter = TextRegion.intersect(r1, r2);
assertNotNull(inter, "Intersection of " + r1 + " and " + r2 + " must exist");
TextRegion symmetric = TextRegion.intersect(r2, r1);
assertEquals(inter, symmetric, "Intersection of " + r1 + " and " + r2 + " must be symmetric");
return inter;
}
private TextRegion doUnion(TextRegion r1, TextRegion r2) {
TextRegion union = TextRegion.union(r1, r2);
assertTrue(union.contains(r1), "Union of " + r1 + " and " + r2 + " must contain first region");
assertTrue(union.contains(r2), "Union of " + r1 + " and " + r2 + " must contain second region");
TextRegion symmetric = TextRegion.union(r2, r1);
assertEquals(union, symmetric, "Union of " + r1 + " and " + r2 + " must be symmetric");
return union;
}
private void noIntersect(TextRegion r1, TextRegion r2) {
TextRegion inter = TextRegion.intersect(r1, r2);
assertNull(inter, "Intersection of " + r1 + " and " + r2 + " must not exist");
TextRegion symmetric = TextRegion.intersect(r2, r1);
assertEquals(inter, symmetric, "Intersection of " + r1 + " and " + r2 + " must be symmetric");
}
}
| 8,500 | 26.334405 | 104 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
class NioTextFileTest {
@TempDir
private Path tempDir;
@Test
void zipFileDisplayName() throws Exception {
Path zipArchive = tempDir.resolve("sources.zip");
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipArchive.toFile()))) {
ZipEntry zipEntry = new ZipEntry("path/inside/someSource.dummy");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write("dummy text".getBytes(StandardCharsets.UTF_8));
zipOutputStream.closeEntry();
}
PMDConfiguration config = new PMDConfiguration();
config.setReporter(new TestMessageReporter());
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
pmd.files().addZipFileWithContent(zipArchive);
List<TextFile> collectedFiles = pmd.files().getCollectedFiles();
assertEquals(1, collectedFiles.size());
TextFile textFile = collectedFiles.get(0);
assertEquals(zipArchive.toAbsolutePath() + "!/path/inside/someSource.dummy",
pmd.fileNameRenderer().getDisplayName(textFile));
}
}
}
| 1,706 | 33.836735 | 112 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFileContentTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
class TextFileContentTest {
// in real life it's System.lineSeparator()
// to make the class more testable (and avoid some test failures being hidden depending on the platform),
// we use this dummy value
private static final String LINESEP_SENTINEL = ":fallback:";
@ParameterizedTest
@EnumSource
void testMixedDelimiters(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\r\nb\n\rc");
assertEquals(Chars.wrap("a\nb\n\nc"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testFormFeedIsNotNewline(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\f\nb\nc");
assertEquals(Chars.wrap("a\f\nb\nc"), content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@Test
void testNormTextPreservation() {
Chars input = Chars.wrap("a\nb\nc");
TextFileContent content = TextFileContent.fromCharSeq(input);
assertSame(input, content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testBomElimination(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("\ufeffabc");
Chars normalizedText = content.getNormalizedText();
assertEquals(Chars.wrap("abc"), normalizedText);
// This means the string underlying the Chars does not start with the bom marker.
// It's useful for performance to have `textDocument.getText().toString()` be O(1),
// and not create a new string.
assertTrue(normalizedText.isFullString(), "should be full string");
assertSame(normalizedText.toString(), normalizedText.toString());
}
@ParameterizedTest
@EnumSource
void testNoExplicitLineMarkers(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a");
assertEquals(Chars.wrap("a"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testEmptyFile(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("");
assertEquals(Chars.wrap(""), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@Test
void testCrlfSplitOnBuffer() throws IOException {
StringReader reader = new StringReader("a\r\nb");
// now the buffer is of size 2, so we read first [a\r] then [\nb]
// but there is a single line
TextFileContent content = TextFileContent.normalizingRead(reader, 2, System.lineSeparator());
assertEquals(Chars.wrap("a\nb"), content.getNormalizedText());
assertEquals("\r\n", content.getLineTerminator());
}
@Test
void testCrSplitOnBufferFp() throws IOException {
StringReader reader = new StringReader("a\rb\n");
// the buffer is of size 2, so we read first [a\r] then [b\n]
// the \r is a line terminator on its own
TextFileContent content = TextFileContent.normalizingRead(reader, 2, LINESEP_SENTINEL);
assertEquals(Chars.wrap("a\nb\n"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testCrCr(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\r\rb");
assertEquals(Chars.wrap("a\n\nb"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testCrIsEol(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\rb\rdede");
assertEquals(Chars.wrap("a\nb\ndede"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
@ParameterizedTest
@EnumSource
void testLfAtStartOfFile(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("\nohio");
assertEquals(Chars.wrap("\nohio"), content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@Test
void testCrCrSplitBuffer() throws IOException {
StringReader reader = new StringReader("a\r\r");
// the buffer is of size 2, so we read first [a\r] then [\ro]
// the \r is not a line terminator though
TextFileContent content = TextFileContent.normalizingRead(reader, 2, LINESEP_SENTINEL);
assertEquals(Chars.wrap("a\n\n"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
enum TextContentOrigin {
INPUT_STREAM {
@Override
TextFileContent normalize(String text) throws IOException {
Charset charset = StandardCharsets.UTF_8;
byte[] input = text.getBytes(charset);
TextFileContent content;
try (ByteArrayInputStream bar = new ByteArrayInputStream(input)) {
content = TextFileContent.fromInputStream(bar, charset, LINESEP_SENTINEL);
}
return content;
}
},
READER {
@Override
TextFileContent normalize(String input) throws IOException {
return TextFileContent.normalizingRead(new StringReader(input), 4096, LINESEP_SENTINEL);
}
},
STRING {
@Override
TextFileContent normalize(String input) throws IOException {
return TextFileContent.normalizeCharSeq(input, LINESEP_SENTINEL);
}
};
abstract TextFileContent normalize(String input) throws IOException;
}
}
| 6,615 | 39.341463 | 109 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SourceCodePositionerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* Unit test for {@link SourceCodePositioner}.
*/
class SourceCodePositionerTest {
@Test
void testLineNumberFromOffset() {
final String source = "abcd\ndefghi\n\rjklmn\ropq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
int offset;
offset = source.indexOf('a');
assertEquals(1, positioner.lineNumberFromOffset(offset));
assertEquals(1, positioner.columnFromOffset(1, offset));
offset = source.indexOf('b');
assertEquals(1, positioner.lineNumberFromOffset(offset));
assertEquals(2, positioner.columnFromOffset(1, offset));
offset = source.indexOf('e');
assertEquals(2, positioner.lineNumberFromOffset(offset));
assertEquals(2, positioner.columnFromOffset(2, offset));
offset = source.indexOf('q');
assertEquals(3, positioner.lineNumberFromOffset(offset));
assertEquals(10, positioner.columnFromOffset(3, offset));
offset = source.length();
assertEquals(3, positioner.lineNumberFromOffset(offset));
assertEquals(11, positioner.columnFromOffset(3, offset));
offset = source.length() + 1;
assertEquals(-1, positioner.lineNumberFromOffset(offset));
assertEquals(-1, positioner.columnFromOffset(3, offset));
}
@Test
void testOffsetFromLineColumn() {
final String source = "abcd\ndefghi\r\njklmn\nopq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
assertEquals(0, positioner.offsetFromLineColumn(1, 1));
assertEquals(2, positioner.offsetFromLineColumn(1, 3));
assertEquals("abcd\n".length(), positioner.offsetFromLineColumn(2, 1));
assertEquals("abcd\nd".length(), positioner.offsetFromLineColumn(2, 2));
assertEquals("abcd\nde".length(), positioner.offsetFromLineColumn(2, 3));
assertEquals("abcd\ndef".length(), positioner.offsetFromLineColumn(2, 4));
assertEquals("abcd\ndefghi\r\n".length(), positioner.offsetFromLineColumn(3, 1));
assertEquals(source.length(), positioner.offsetFromLineColumn(4, 4));
assertEquals(-1, positioner.offsetFromLineColumn(4, 5));
assertEquals(source.length(), positioner.offsetFromLineColumn(5, 1));
assertEquals(-1, positioner.offsetFromLineColumn(5, 2));
}
@Test
void testWrongOffsets() {
final String source = "abcd\ndefghi\r\njklmn\nopq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
assertEquals(0, positioner.offsetFromLineColumn(1, 1));
assertEquals(1, positioner.offsetFromLineColumn(1, 2));
assertEquals(2, positioner.offsetFromLineColumn(1, 3));
assertEquals(3, positioner.offsetFromLineColumn(1, 4));
assertEquals(4, positioner.offsetFromLineColumn(1, 5));
assertEquals(5, positioner.offsetFromLineColumn(1, 6)); // this is right after the '\n'
assertEquals(-1, positioner.offsetFromLineColumn(1, 7));
}
@Test
void testEmptyDocument() {
SourceCodePositioner positioner = SourceCodePositioner.create("");
assertEquals(0, positioner.offsetFromLineColumn(1, 1));
assertEquals(-1, positioner.offsetFromLineColumn(1, 2));
assertEquals(1, positioner.lineNumberFromOffset(0));
assertEquals(-1, positioner.lineNumberFromOffset(1));
assertEquals(1, positioner.columnFromOffset(1, 0));
assertEquals(-1, positioner.columnFromOffset(1, 1));
}
@Test
void testDocumentStartingWithNl() {
SourceCodePositioner positioner = SourceCodePositioner.create("\n");
assertEquals(0, positioner.offsetFromLineColumn(1, 1));
assertEquals(1, positioner.offsetFromLineColumn(1, 2));
assertEquals(-1, positioner.offsetFromLineColumn(1, 3));
assertEquals(1, positioner.lineNumberFromOffset(0));
assertEquals(2, positioner.lineNumberFromOffset(1));
assertEquals(-1, positioner.lineNumberFromOffset(2));
}
@Test
void lineToOffsetMappingWithLineFeedShouldSucceed() {
final String code = "public static int main(String[] args) {\n"
+ "int var;\n"
+ "}";
SourceCodePositioner positioner = SourceCodePositioner.create(code);
assertArrayEquals(new int[] { 0, 40, 49, 50 }, positioner.getLineOffsets());
}
@Test
void lineToOffsetMappingWithCarriageReturnFeedLineFeedShouldSucceed() {
final String code = "public static int main(String[] args) {\r\n"
+ "int var;\r\n"
+ "}";
SourceCodePositioner positioner = SourceCodePositioner.create(code);
assertArrayEquals(new int[] { 0, 41, 51, 52 }, positioner.getLineOffsets());
}
@Test
void lineToOffsetMappingWithMixedLineSeparatorsShouldSucceed() {
final String code = "public static int main(String[] args) {\r\n"
+ "int var;\n"
+ "}";
SourceCodePositioner positioner = SourceCodePositioner.create(code);
assertArrayEquals(new int[] { 0, 41, 50, 51 }, positioner.getLineOffsets());
}
}
| 5,448 | 33.707006 | 95 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import net.sourceforge.pmd.lang.LanguageVersion;
/**
* Makes {@link StringTextFile} publicly available for unit tests.
*/
public class SimpleTestTextFile extends StringTextFile {
public SimpleTestTextFile(String content, FileId fileId, LanguageVersion languageVersion) {
super(content, fileId, languageVersion);
}
}
| 468 | 25.055556 | 95 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextPos2dTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
class TextPos2dTest {
@Test
void testToString() {
TextPos2d pos = TextPos2d.pos2d(1, 2);
assertEquals(
"line 1, column 2",
pos.toDisplayStringInEnglish()
);
assertEquals(
"1:2",
pos.toDisplayStringWithColon()
);
assertEquals(
"(line=1, column=2)",
pos.toTupleString()
);
assertThat(pos.toString(), containsString("!debug only!"));
}
@Test
void testEquals() {
TextPos2d pos = TextPos2d.pos2d(1, 1);
TextPos2d pos2 = TextPos2d.pos2d(1, 2);
assertNotEquals(pos, pos2);
assertEquals(pos, TextPos2d.pos2d(1, 1));
assertEquals(pos2, pos2);
}
@Test
void testCompareTo() {
TextPos2d pos = TextPos2d.pos2d(1, 1);
TextPos2d pos2 = TextPos2d.pos2d(1, 2);
TextPos2d pos3 = TextPos2d.pos2d(2, 1);
assertEquals(-1, pos.compareTo(pos2));
assertEquals(-1, pos.compareTo(pos3));
assertEquals(-1, pos2.compareTo(pos3));
assertEquals(1, pos2.compareTo(pos));
assertEquals(0, pos.compareTo(pos));
}
}
| 1,600 | 26.135593 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextDocumentTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyVersion;
import static net.sourceforge.pmd.lang.document.TextPos2d.pos2d;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
class TextDocumentTest {
@Test
void testSingleLineRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, "bonjour".length());
assertEquals(0, region.getStartOffset());
assertEquals("bonjour".length(), region.getLength());
assertEquals("bonjour".length(), region.getEndOffset());
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(1, withLines.getEndLine());
assertEquals(1, withLines.getStartColumn());
assertEquals(1 + "bonjour".length(), withLines.getEndColumn());
assertEquals("bonjour".length(), withLines.getEndColumn() - withLines.getStartColumn());
}
@Test
void testRegionAtEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, "bonjour\n".length());
assertEquals("bonjour\n", doc.sliceOriginalText(region).toString());
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(1, withLines.getEndLine());
assertEquals(1, withLines.getStartColumn());
assertEquals(1 + "bonjour\n".length(), withLines.getEndColumn());
assertEquals("bonjour\n".length(), withLines.getEndColumn() - withLines.getStartColumn());
}
@Test
void testEmptyRegionAtEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
// ^ The caret position right after the \n
// We consider it's part of the next line
TextRegion region = TextRegion.fromOffsetLength("bonjour\n".length(), 0);
assertEquals("", doc.sliceOriginalText(region).toString());
FileLocation withLines = doc.toLocation(region);
assertEquals(2, withLines.getStartLine());
assertEquals(2, withLines.getEndLine());
assertEquals(1, withLines.getStartColumn());
assertEquals(1, withLines.getEndColumn());
}
@Test
void testRegionForEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
// [ [ The region containing the \n
// We consider it ends on the same line, not the next one
TextRegion region = TextRegion.fromOffsetLength("bonjour".length(), 1);
assertEquals("\n", doc.sliceOriginalText(region).toString());
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(1, withLines.getEndLine());
assertEquals(1 + "bonjour".length(), withLines.getStartColumn());
assertEquals(1 + "bonjour\n".length(), withLines.getEndColumn());
}
@Test
void testRegionAtEndOfFile() {
TextDocument doc = TextDocument.readOnlyString("flemme", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, doc.getLength());
assertEquals(doc.getText(), doc.sliceOriginalText(region));
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(1, withLines.getEndLine());
assertEquals(1, withLines.getStartColumn());
assertEquals(1 + doc.getLength(), withLines.getEndColumn());
}
@Test
void testMultiLineRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength("bonjou".length(), "r\noha\ntri".length());
assertEquals("bonjou".length(), region.getStartOffset());
assertEquals("r\noha\ntri".length(), region.getLength());
assertEquals("bonjour\noha\ntri".length(), region.getEndOffset());
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(3, withLines.getEndLine());
assertEquals(1 + "bonjou".length(), withLines.getStartColumn());
assertEquals(1 + "tri".length(), withLines.getEndColumn());
}
@Test
void testLineColumnFromOffset() {
TextDocument doc = TextDocument.readOnlyString("ab\ncd\n", dummyVersion());
assertPos2dEqualsAt(doc, 0, "a", pos2d(1, 1), true);
assertPos2dEqualsAt(doc, 0, "a", pos2d(1, 1), false);
assertPos2dEqualsAt(doc, 1, "b", pos2d(1, 2), true);
assertPos2dEqualsAt(doc, 2, "\n", pos2d(1, 3), true);
assertPos2dEqualsAt(doc, 3, "c", pos2d(2, 1), true);
assertPos2dEqualsAt(doc, 3, "c", pos2d(1, 4), false);
assertPos2dEqualsAt(doc, 4, "d", pos2d(2, 2), true);
assertPos2dEqualsAt(doc, 5, "\n", pos2d(2, 3), true);
// EOF caret position
assertEquals(pos2d(3, 1), doc.lineColumnAtOffset(6));
assertThrows(IndexOutOfBoundsException.class, () -> doc.lineColumnAtOffset(7));
}
private void assertPos2dEqualsAt(TextDocument doc, int offset, String c, TextPos2d pos, boolean inclusive) {
Chars slicedChar = doc.sliceTranslatedText(TextRegion.fromOffsetLength(offset, 1));
assertEquals(c, slicedChar.toString());
assertEquals(pos, doc.lineColumnAtOffset(offset, inclusive));
}
@Test
void testEmptyRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength("bonjour".length(), 0);
assertEquals("bonjour".length(), region.getStartOffset());
assertEquals(0, region.getLength());
assertEquals(region.getStartOffset(), region.getEndOffset());
FileLocation withLines = doc.toLocation(region);
assertEquals(1, withLines.getStartLine());
assertEquals(1, withLines.getEndLine());
assertEquals(1 + "bonjour".length(), withLines.getStartColumn());
assertEquals(1 + "bonjour".length(), withLines.getEndColumn());
}
@Test
void testLineRange() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
assertEquals(Chars.wrap("bonjour\n"), doc.sliceTranslatedText(doc.createLineRange(1, 1)));
assertEquals(Chars.wrap("bonjour\noha\n"), doc.sliceTranslatedText(doc.createLineRange(1, 2)));
assertEquals(Chars.wrap("oha\n"), doc.sliceTranslatedText(doc.createLineRange(2, 2)));
assertEquals(Chars.wrap("oha\ntristesse"), doc.sliceTranslatedText(doc.createLineRange(2, 3)));
assertThrows(IndexOutOfBoundsException.class, () -> doc.createLineRange(2, 1));
assertThrows(IndexOutOfBoundsException.class, () -> doc.createLineRange(1, 5));
assertThrows(IndexOutOfBoundsException.class, () -> doc.createLineRange(0, 2));
}
@ParameterizedTest
@MethodSource("documentProvider")
void testEntireRegion(TextDocument doc) {
assertEquals(TextRegion.fromOffsetLength(0, doc.getLength()),
doc.getEntireRegion(),
"getEntireRegion should return something based on length");
}
@ParameterizedTest
@MethodSource("documentProvider")
void testReader(TextDocument doc) throws IOException {
assertEquals(doc.getText().toString(),
IOUtil.readToString(doc.newReader()),
"NewReader should read the text");
}
@Test
void testRegionOutOfBounds() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
assertThrows(AssertionError.class, () -> TextRegion.isValidRegion(0, 40, doc));
}
@SuppressWarnings("resource")
static Object[] documentProvider() {
LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
return new TextDocument[] {
TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion),
TextDocument.readOnlyString("bonjour\n", dummyVersion),
TextDocument.readOnlyString("\n", dummyVersion),
TextDocument.readOnlyString("", dummyVersion),
};
}
}
| 9,130 | 40.694064 | 127 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TestMessageReporter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
/**
* @author Clément Fournier
*/
public class TestMessageReporter extends SimpleMessageReporter {
private static final Logger LOG = LoggerFactory.getLogger(TestMessageReporter.class.getName());
public TestMessageReporter() {
super(LOG);
}
}
| 525 | 21.869565 | 99 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
class FileLocationTest {
public static final FileId FNAME = FileId.fromPathLikeString("fname");
@Test
void testSimple() {
FileLocation loc = FileLocation.range(FNAME, TextRange2d.range2d(1, 1, 1, 2));
assertEquals(FNAME, loc.getFileId());
assertEquals(1, loc.getStartLine());
assertEquals(1, loc.getStartColumn());
assertEquals(1, loc.getEndLine());
assertEquals(2, loc.getEndColumn());
}
@Test
void testToRange() {
TextRange2d range2d = TextRange2d.range2d(1, 1, 1, 2);
FileLocation loc = FileLocation.range(FNAME, range2d);
assertEquals(range2d, loc.toRange2d());
}
@Test
void testToString() {
FileLocation loc = FileLocation.range(FNAME, TextRange2d.range2d(1, 1, 1, 2));
assertEquals(
"line 1, column 1",
loc.startPosToString()
);
assertEquals(
"fname:1:1",
loc.startPosToStringWithFile()
);
assertThat(loc.toString(), containsString("!debug only!"));
}
}
| 1,450 | 25.87037 | 86 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileIdTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
class FileIdTest {
// note we can't hardcode the expected paths because they look different on win and nix
@Test
void testFromPath() {
Path path = Paths.get("/a");
Path absPath = path.toAbsolutePath();
FileId fileId = FileId.fromPath(path);
checkId(fileId, absPath.toString(), "a", path.toUri().toString(), path.toString());
}
@Test
void testFromUri() {
Path absPath = Paths.get("/a/b.c");
String uriStr = absPath.toUri().toString();
FileId fileId = FileId.fromURI(uriStr);
checkId(fileId, absPath.toAbsolutePath().toString(), "b.c", uriStr, absPath.toAbsolutePath().toString());
}
@Test
void testFromUriForJar() {
Path zipPath = Paths.get("/a/b.zip");
String uriStr = "jar:" + zipPath.toUri() + "!/x/c.d";
FileId fileId = FileId.fromURI(uriStr);
String absLocalPath = "/x/c.d".replace('/', File.separatorChar);
checkId(fileId, absLocalPath, "c.d", uriStr, "/x/c.d");
checkId(fileId.getParentFsPath(), zipPath.toAbsolutePath().toString(), "b.zip", zipPath.toUri().toString(), zipPath.toAbsolutePath().toString());
}
private static void checkId(FileId fileId, String absPath, String fileName, String uri, String originalPath) {
assertNotNull(fileId);
assertEquals(absPath, fileId.getAbsolutePath(), "absolute path");
assertEquals(fileName, fileId.getFileName(), "file name");
assertEquals(uri, fileId.getUriString(), "uri");
assertEquals(originalPath, fileId.getOriginalPath(), "original path");
}
}
| 2,010 | 33.672414 | 153 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyVersion;
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.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.util.datasource.DataSource;
import net.sourceforge.pmd.util.datasource.FileDataSource;
class TextFilesTest {
@TempDir
Path tempDir;
@Test
void testNioFile() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(file.toAbsolutePath().toUri().toString(), tf.getFileId().getUriString());
assertEquals(file.toString(), tf.getFileId().getOriginalPath());
assertEquals(file.getFileName().toString(), tf.getFileId().getFileName());
assertEquals(dummyVersion(), tf.getLanguageVersion());
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
}
@Test
void testEquals() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content").toAbsolutePath();
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
try (TextFile stringTf = TextFile.forCharSeq("some content", FileId.fromPath(file), dummyVersion())) {
assertEquals(tf.getFileId(), stringTf.getFileId());
// despite same path id, they are different implementations
assertNotEquals(tf, stringTf);
assertNotEquals(stringTf, tf);
// identical, but string text files use identity
assertNotEquals(stringTf, TextFile.forCharSeq("some content", FileId.fromPath(file), dummyVersion()));
// those are identical so are equals
assertNotSame(tf, tfPrime);
assertEquals(tf, tfPrime);
assertEquals(tfPrime, tf);
assertEquals(tf.hashCode(), tfPrime.hashCode());
}
}
}
}
@Test
void testStringDataSourceCompat() throws IOException {
DataSource ds = DataSource.forString("text", "filename.dummy");
PMDConfiguration config = new PMDConfiguration();
try (TextFile tf = TextFile.dataSourceCompat(ds, config)) {
assertEquals("filename.dummy", tf.getFileId().getFileName());
assertEquals(DummyLanguageModule.getInstance().getDefaultVersion(), tf.getLanguageVersion());
assertEquals(Chars.wrap("text"), tf.readContents().getNormalizedText());
}
}
@Test
void testFileDataSourceCompat() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
DataSource ds = new FileDataSource(file.toFile());
PMDConfiguration config = new PMDConfiguration();
config.setForceLanguageVersion(DummyLanguageModule.getInstance().getDefaultVersion());
try (TextFile tf = TextFile.dataSourceCompat(ds, config)) {
assertEquals(ds.getNiceFileName(false, null), tf.getFileId().getOriginalPath());
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
}
@Test
void testFileDataSourceCompatWithEncoding() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_16BE, "some content");
DataSource ds = new FileDataSource(file.toFile());
PMDConfiguration config = new PMDConfiguration();
config.setForceLanguageVersion(DummyLanguageModule.getInstance().getDefaultVersion());
config.setSourceEncoding(StandardCharsets.UTF_16BE.name());
try (TextFile tf = TextFile.dataSourceCompat(ds, config)) {
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
// different encoding to produce garbage, to make sure encoding is used
config.setSourceEncoding(StandardCharsets.UTF_16LE.name());
try (TextFile tf = TextFile.dataSourceCompat(ds, config)) {
assertNotEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
}
@Test
void testNioFileWrite() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
assertFalse(tf.isReadOnly(), "readonly");
// write with CRLF
tf.writeContents(
TextFileContent.fromCharSeq("new content\r\n")
);
TextFileContent read = tf.readContents();
// is normalized to LF when rereading
assertEquals(Chars.wrap("new content\n"), read.getNormalizedText());
// but line terminator is detected as CRLF
assertEquals("\r\n", read.getLineTerminator());
tf.writeContents(
TextFileContent.fromCharSeq("new content\n")
);
assertEquals(Chars.wrap("new content\n"), tf.readContents().getNormalizedText());
}
}
@Test
void testNioFileExplicitReadOnly() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion())
.asReadOnly().build()) {
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
}
}
@Test
void testNioFileCanBeReadMultipleTimes() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
}
@Test
void testNioFileBuilder() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion())
.build()) {
assertEquals(file.toAbsolutePath().toUri().toString(), tf.getFileId().getUriString());
assertEquals(dummyVersion(), tf.getLanguageVersion());
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
}
}
@Test
void testNioFileEscape() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText());
}
}
@Test
void testReaderFile() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), FileId.UNKNOWN, dummyVersion())) {
assertEquals(FileId.UNKNOWN, tf.getFileId());
assertEquals(dummyVersion(), tf.getLanguageVersion());
assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText());
}
}
@Test
void testReaderFileIsReadOnly() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), FileId.UNKNOWN, dummyVersion())) {
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
}
}
@Test
void testStringFileEscape() throws IOException {
try (TextFile tf = TextFile.forCharSeq("cont\r\nents", FileId.UNKNOWN, dummyVersion())) {
assertEquals(FileId.UNKNOWN, tf.getFileId());
assertEquals(dummyVersion(), tf.getLanguageVersion());
assertEquals(Chars.wrap("cont\nents"), tf.readContents().getNormalizedText());
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
}
}
@Test
void testStringFileCanBeReadMultipleTimes() throws IOException {
try (TextFile tf = TextFile.forCharSeq("contents", FileId.UNKNOWN, dummyVersion())) {
assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText());
assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText());
assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText());
}
}
@Test
void testStringFileIsReadonly() throws IOException {
try (TextFile tf = TextFile.forCharSeq("contents", FileId.UNKNOWN, dummyVersion())) {
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
}
}
private @NonNull Path makeTmpFile(Charset charset, String content) throws IOException {
Path file = Files.createTempFile(tempDir, null, null);
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(content);
}
return file;
}
}
| 10,751 | 43.065574 | 135 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/CharsTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.util.CollectionUtil;
import net.sourceforge.pmd.util.IteratorUtil;
/**
*
*/
class CharsTest {
@Test
void wrapStringRoundTrip() {
String s = "ooo";
assertSame(s, Chars.wrap(s).toString());
}
@Test
void wrapCharsRoundTrip() {
Chars s = Chars.wrap("ooo");
assertSame(s, Chars.wrap(s));
}
@Test
void appendChars() {
StringBuilder sb = new StringBuilder();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
bc.appendChars(sb);
assertEquals("bc", sb.toString());
}
@Test
void appendCharsWithOffsets() {
StringBuilder sb = new StringBuilder();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
bc.appendChars(sb, 0, 1);
assertEquals("b", sb.toString());
}
@Test
void toStringBuilder() {
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
assertEquals("bc", bc.toStringBuilder().toString());
}
@Test
void write() throws IOException {
StringWriter writer = new StringWriter();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
bc.write(writer, 0, 1);
assertEquals("b", writer.toString());
writer = new StringWriter();
bc.writeFully(writer);
assertEquals("bc", writer.toString());
}
@Test
void getChars() {
char[] arr = new char[4];
Chars bc = Chars.wrap("abcd").slice(1, 2);
bc.getChars(0, arr, 1, 2);
assertArrayEquals(arr, new char[] { 0, 'b', 'c', 0 });
assertThrows(IndexOutOfBoundsException.class, () -> bc.getChars(2, arr, 0, 1));
assertThrows(IndexOutOfBoundsException.class, () -> bc.getChars(-1, arr, 0, 1));
assertThrows(IndexOutOfBoundsException.class, () -> bc.getChars(0, arr, 0, 3));
assertThrows(IndexOutOfBoundsException.class, () -> bc.getChars(0, arr, 4, 3));
assertThrows(NullPointerException.class, () -> bc.getChars(0, null, 0, 0));
}
@Test
void indexOf() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.indexOf('b', 0));
assertEquals(1, bc.indexOf('c', 0));
assertEquals(-1, bc.indexOf('b', 1));
assertEquals(-1, bc.indexOf('d', 0));
assertEquals(-1, bc.indexOf('x', 0));
assertEquals(-1, bc.indexOf('a', -1));
}
@Test
void indexOfString() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.indexOf("b", 0));
assertEquals(0, bc.indexOf("bc", 0));
assertEquals(1, bc.indexOf("c", 0));
assertEquals(-1, bc.indexOf("b", 1));
assertEquals(-1, bc.indexOf("bc", 1));
assertEquals(-1, bc.indexOf("d", 0));
assertEquals(-1, bc.indexOf("bcd", 0));
assertEquals(-1, bc.indexOf("x", 0));
assertEquals(-1, bc.indexOf("ab", -1));
bc = Chars.wrap("aaaaabcdbxdb").slice(5, 5);
// -----
assertEquals(3, bc.indexOf("bx", 0));
bc = Chars.wrap("aaaaabcbxdb").slice(5, 5);
// -----
assertEquals(2, bc.indexOf("bx", 0));
}
@Test
void lastIndexOf() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.lastIndexOf('b', 0));
assertEquals(0, bc.lastIndexOf('b', 1));
assertEquals(1, bc.lastIndexOf('c', 1));
assertEquals(-1, bc.lastIndexOf('c', 0));
assertEquals(-1, bc.lastIndexOf('d', 0));
assertEquals(-1, bc.lastIndexOf('x', 0));
assertEquals(-1, bc.lastIndexOf('a', -1));
assertEquals(-1, bc.lastIndexOf('a', 0));
assertEquals(-1, bc.lastIndexOf('a', 1));
}
@Test
void startsWith() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
assertTrue(bc.startsWith("bc"));
assertTrue(bc.startsWith("bc", 0));
assertTrue(bc.startsWith("c", 1));
assertTrue(bc.startsWith('c', 1)); //with a char
assertTrue(bc.startsWith("", 1));
assertTrue(bc.startsWith("", 0));
assertFalse(bc.startsWith("c", 0));
assertFalse(bc.startsWith('c', 0)); //with a char
assertFalse(bc.startsWith("bcd", 0));
assertFalse(bc.startsWith("xcd", 0));
assertFalse(bc.startsWith("b", -1));
assertFalse(bc.startsWith('b', -1)); //with a char
assertFalse(bc.startsWith("", -1));
assertFalse(bc.startsWith("", 5));
}
@Test
void removeSuffix() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
// --
assertEquals("bc", bc.toString());
assertEquals("b", bc.removeSuffix("c").toString());
assertEquals("", bc.removeSuffix("bc").toString());
bc = Chars.wrap("aaaaaaa").slice(2, 3);
// ---
assertEquals("", bc.removeSuffix("aaa").toString());
assertEquals("aaa", bc.removeSuffix("aaaa").toString());
}
@Test
void removePrefix() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
// --
assertEquals("bc", bc.toString());
assertEquals("bc", bc.removePrefix("c").toString());
assertEquals("", bc.removePrefix("bc").toString());
assertEquals("c", bc.removePrefix("b").toString());
bc = Chars.wrap("aaaaaaa").slice(2, 3);
// ---
assertEquals("aaa", bc.toString());
assertEquals("", bc.removePrefix("aaa").toString());
assertEquals("aaa", bc.removePrefix("aaaa").toString());
}
@Test
void trimNoop() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
assertEquals("bc", bc.toString());
assertEquals("bc", bc.trimStart().toString());
assertEquals("bc", bc.trimEnd().toString());
assertEquals("bc", bc.trim().toString());
}
@Test
void trimStartAndEnd() {
Chars bc = Chars.wrap("a bc db").slice(1, 6);
// ------
assertEquals(" bc ", bc.toString());
assertEquals("bc ", bc.trimStart().toString());
assertEquals(" bc", bc.trimEnd().toString());
assertEquals("bc", bc.trim().toString());
}
@Test
void charAt() {
Chars bc = Chars.wrap("a bc db").slice(1, 6);
// ------
assertEquals(' ', bc.charAt(0));
assertEquals('b', bc.charAt(3));
assertEquals('c', bc.charAt(4));
assertEquals(' ', bc.charAt(5));
assertThrows(IndexOutOfBoundsException.class, () -> bc.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> bc.charAt(7));
}
@Test
void linesTest() {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
List<String> lines = CollectionUtil.map(bc.lines(), Chars::toString);
assertEquals(listOf(" ", " ", "bc "), lines);
}
@Test
void linesTest2() {
Chars bc = Chars.wrap("aa\n");
List<String> lines = CollectionUtil.map(bc.lines(), Chars::toString);
assertEquals(listOf("aa"), lines);
}
@Test
void linesStreamTest() {
Chars bc = Chars.wrap("aa\nb\rded\r\nlff");
List<String> lines = bc.lineStream().map(Chars::toString).collect(Collectors.toList());
assertEquals(listOf("aa", "b", "ded", "lff"), lines);
}
@Test
void linesTest3WithCr() {
Chars bc = Chars.wrap("aa\rb");
List<String> lines = CollectionUtil.map(bc.lines(), Chars::toString);
assertEquals(listOf("aa", "b"), lines);
}
@Test
void testEqualsHashCode() {
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
assertEquals(Chars.wrap("a_b_c"), chars);
assertNotEquals("a_b_c", chars);
assertEquals(Chars.wrap("a_b_c").hashCode(), chars.hashCode());
assertEquals(chars, chars);
assertEquals("a_b_c".hashCode(), Chars.wrap("a_b_c").hashCode());
assertEquals("a_b_c".hashCode(), chars.hashCode());
}
@Test
void testContentEquals() {
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
assertTrue(chars.contentEquals("a_b_c"));
assertTrue(chars.contentEquals(Chars.wrap("a_b_c")));
assertFalse(chars.contentEquals("a_b_c_--"));
assertFalse(chars.contentEquals(Chars.wrap("a_b_c_")));
assertFalse(chars.contentEquals(Chars.wrap("a_b-c")));
assertTrue(chars.contentEquals(Chars.wrap("A_B_C"), true));
}
@Test
void testSplits() {
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
assertEquals("a_b_c", chars.toString());
testSplits(chars, "_");
testSplits(chars, "a");
testSplits(chars, "b");
testSplits(chars, "c");
assertEquals(listOf("", "_b_c"), listSplits(chars, "a"));
chars = chars.subSequence(1, 5);
assertEquals("_b_c", chars.toString());
assertEquals(listOf("", "b", "c"), listSplits(chars, "_"));
testSplits(Chars.wrap("abc"), "");
testSplits(Chars.wrap(""), "");
}
private List<String> listSplits(Chars chars, String regex) {
Pattern pattern = Pattern.compile(regex);
Iterator<Chars> splits = chars.splits(pattern).iterator();
return IteratorUtil.toList(IteratorUtil.map(splits, Chars::toString));
}
private void testSplits(Chars chars, String regex) {
List<String> splitList = listSplits(chars, regex);
List<String> expected = Arrays.asList(chars.toString().split(regex));
assertEquals(expected, splitList, "Split should behave like String#split");
}
@Test
void testSlice() {
// slice is offset + length
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
assertEquals(Chars.wrap("_b_"), chars.slice(1, 3));
assertThrows(IndexOutOfBoundsException.class, () -> chars.slice(0, -1));
assertThrows(IndexOutOfBoundsException.class, () -> chars.slice(0, 6));
}
@Test
void testSubsequence() {
// subsequence is start + end
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
assertEquals(Chars.wrap("_b"), chars.subSequence(1, 3));
assertThrows(IndexOutOfBoundsException.class, () -> chars.slice(0, -1));
assertThrows(IndexOutOfBoundsException.class, () -> chars.slice(0, 6));
}
@Test
void testSubstring() {
// substring is start + end
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
assertEquals("_b", chars.substring(1, 3));
assertThrows(IndexOutOfBoundsException.class, () -> chars.substring(0, -1));
assertThrows(IndexOutOfBoundsException.class, () -> chars.substring(0, 6));
}
@Test
void testTrimBlankLines() {
assertTrimBlankLinesEquals(" \n \n abc \n \n de \n \n ",
" abc \n \n de ");
assertTrimBlankLinesEquals("", "");
}
private void assertTrimBlankLinesEquals(String input, String expected) {
Chars actual = Chars.wrap(input).trimBlankLines();
assertEquals(Chars.wrap(expected), actual);
}
@Test
void testReaderSingleChars() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
try (Reader reader = bc.newReader()) {
assertEquals(' ', reader.read());
assertEquals('\n', reader.read());
assertEquals(' ', reader.read());
assertEquals(' ', reader.read());
assertEquals('\r', reader.read());
assertEquals('\n', reader.read());
assertEquals('b', reader.read());
assertEquals('c', reader.read());
assertEquals(' ', reader.read());
assertEquals(-1, reader.read());
}
}
@Test
void testReaderBuffer() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
char[] cbuf = new char[4];
try (Reader reader = bc.newReader()) {
assertEquals(4, reader.read(cbuf));
assertCharBufEquals(" \n ", cbuf);
assertEquals(4, reader.read(cbuf));
assertCharBufEquals("\r\nbc", cbuf);
assertEquals(1, reader.read(cbuf));
assertCharBufEquals(" \nbc", cbuf);
assertEquals(-1, reader.read(cbuf));
}
}
@Test
void testReaderSlicedBuffer() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
// use \0 as padding before and after
char[] cbuf = new char[6];
try (Reader reader = bc.newReader()) {
assertEquals(4, reader.read(cbuf, 1, 4));
assertCharBufEquals("\0 \n \0", cbuf);
assertEquals(5, reader.read(cbuf, 1, 5));
assertCharBufEquals("\0\r\nbc ", cbuf);
assertEquals(-1, reader.read(cbuf));
assertEquals(-1, reader.read());
assertEquals(-1, reader.read(cbuf, 1, 4));
}
}
@Test
void testReadClosed() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
Reader reader = bc.newReader();
reader.close();
assertThrows(IOException.class, reader::read);
}
@Test
void testReaderMark() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
try (Reader reader = bc.newReader()) {
assertTrue(reader.markSupported(), "markSupported");
assertEquals('b', reader.read());
assertEquals('c', reader.read());
assertEquals('d', reader.read());
assertEquals('e', reader.read());
reader.mark(10);
assertEquals('f', reader.read());
assertEquals('g', reader.read());
reader.reset();
assertEquals('f', reader.read());
assertEquals('g', reader.read());
reader.reset(); // reset doesn't clear the mark
assertEquals('f', reader.read());
assertEquals('g', reader.read());
}
}
@Test
void testReaderMissingMark() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
try (Reader reader = bc.newReader()) {
assertTrue(reader.markSupported(), "markSupported");
assertEquals('b', reader.read());
assertThrows(IOException.class, reader::reset);
}
}
@Test
void testReaderSkip() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
try (Reader reader = bc.newReader()) {
assertEquals('b', reader.read());
assertEquals('c', reader.read());
assertEquals('d', reader.read());
assertEquals('e', reader.read());
reader.mark(10);
assertEquals(2, reader.skip(2));
assertEquals('h', reader.read());
assertEquals('i', reader.read());
reader.reset();
assertEquals('f', reader.read());
assertEquals('g', reader.read());
}
}
@Test
void testReaderInvalidParams() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
char[] cbuf = new char[4];
try (Reader reader = bc.newReader()) {
assertTrue(reader.markSupported(), "markSupported");
assertEquals('b', reader.read());
assertThrows(NullPointerException.class, () -> reader.read(null, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> reader.read(cbuf, -1, 0));
assertThrows(IndexOutOfBoundsException.class, () -> reader.read(cbuf, 1, 12));
assertThrows(IndexOutOfBoundsException.class, () -> reader.read(cbuf, 1, -1));
}
}
private static void assertCharBufEquals(String expected, char[] cbuf) {
String actual = new String(cbuf);
assertEquals(expected, actual);
}
}
| 17,710 | 31.378428 | 95 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextRange2dTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
class TextRange2dTest {
@Test
void testCtors() {
TextRange2d pos = TextRange2d.range2d(1, 2, 3, 4);
TextRange2d pos2 = TextRange2d.range2d(TextPos2d.pos2d(1, 2), TextPos2d.pos2d(3, 4));
assertEquals(pos, pos2);
}
@Test
void testEquals() {
TextRange2d pos = TextRange2d.range2d(1, 1, 1, 1);
TextRange2d pos2 = TextRange2d.range2d(1, 1, 1, 2);
assertNotEquals(pos, pos2);
assertEquals(pos, pos);
assertEquals(pos2, pos2);
}
@Test
void testCompareTo() {
TextRange2d pos = TextRange2d.range2d(1, 1, 1, 1);
TextRange2d pos2 = TextRange2d.range2d(1, 1, 1, 2);
assertEquals(-1, pos.compareTo(pos2));
assertEquals(1, pos2.compareTo(pos));
assertEquals(0, pos.compareTo(pos));
}
@Test
void testToString() {
TextRange2d range = TextRange2d.range2d(1, 2, 3, 4);
assertEquals(
"1:2-3:4",
range.toDisplayStringWithColon()
);
assertThat(range.toString(), containsString("!debug only!"));
}
}
| 1,531 | 26.357143 | 93 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* @author Clément Fournier
*/
class FileCollectorTest {
@TempDir
private Path tempFolder;
@Test
void testAddFile() throws IOException {
Path foo = newFile(tempFolder, "foo.dummy");
Path bar = newFile(tempFolder, "bar.unknown");
FileCollector collector = newCollector();
assertTrue(collector.addFile(foo), "should be dummy language");
assertFalse(collector.addFile(bar), "should be unknown language");
assertCollected(collector, listOf(FileId.fromPath(foo)));
}
@Test
void testAddFileForceLanguage() throws IOException {
Path bar = newFile(tempFolder, "bar.unknown");
Language dummy = DummyLanguageModule.getInstance();
FileCollector collector = newCollector(dummy.getDefaultVersion());
assertTrue(collector.addFile(bar, dummy), "should be unknown language");
assertCollected(collector, listOf(FileId.fromPath(bar)));
assertNoErrors(collector);
}
@Test
void testAddFileNotExists() {
FileCollector collector = newCollector();
assertFalse(collector.addFile(tempFolder.resolve("does_not_exist.dummy")));
assertEquals(1, collector.getReporter().numErrors());
}
@Test
void testAddFileNotAFile() throws IOException {
Path dir = tempFolder.resolve("src");
Files.createDirectories(dir);
FileCollector collector = newCollector();
assertFalse(collector.addFile(dir));
assertEquals(1, collector.getReporter().numErrors());
}
@Test
void testAddDirectory() throws IOException {
Path root = tempFolder;
Path foo = newFile(root, "src/foo.dummy");
newFile(root, "src/bar.unknown");
Path bar = newFile(root, "src/x/bar.dummy");
FileCollector collector = newCollector();
collector.addDirectory(root.resolve("src"));
assertCollected(collector, listOf(FileId.fromPath(foo), FileId.fromPath(bar)));
}
private Path newFile(Path root, String path) throws IOException {
Path resolved = root.resolve(path);
Files.createDirectories(resolved.getParent());
Files.createFile(resolved);
return resolved;
}
private void assertCollected(FileCollector collector, List<FileId> expected) {
List<FileId> actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getFileId);
assertEquals(expected, actual);
}
private void assertNoErrors(FileCollector collector) {
assertEquals(0, collector.getReporter().numErrors(), "No errors expected");
}
private FileCollector newCollector() {
return newCollector(null);
}
private FileCollector newCollector(LanguageVersion forcedVersion) {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD, forcedVersion);
return FileCollector.newCollector(discoverer, new TestMessageReporter());
}
}
| 3,831 | 30.933333 | 114 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule;
import static net.sourceforge.pmd.PmdCoreTestUtils.setDummyLanguage;
import static net.sourceforge.pmd.ReportTestUtil.getReportForRuleApply;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.DummyNodeWithDeprecatedAttribute;
import net.sourceforge.pmd.lang.document.TextRegion;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class XPathRuleTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@Test
void testAttributeDeprecation10() throws Exception {
testDeprecation(XPathVersion.XPATH_1_0);
}
@Test
void testAttributeDeprecation20() throws Exception {
testDeprecation(XPathVersion.XPATH_2_0);
}
void testDeprecation(XPathVersion version) throws Exception {
XPathRule xpr = makeRule(version, "SomeRule");
DummyNode firstNode = newNode();
String log = SystemLambda.tapSystemErrAndOut(() -> {
// with another rule forked from the same one (in multithreaded processor)
Report report = getReportForRuleApply(xpr, firstNode);
assertEquals(1, report.getViolations().size());
});
assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Size' by XPath rule 'SomeRule'"));
assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Name' by XPath rule 'SomeRule', please use @Image instead"));
log = SystemLambda.tapSystemErrAndOut(() -> {
// with another node
Report report = getReportForRuleApply(xpr, newNode());
assertEquals(1, report.getViolations().size());
});
assertEquals("", log); // no additional warnings
log = SystemLambda.tapSystemErrAndOut(() -> {
// with another rule forked from the same one (in multithreaded processor)
Report report = getReportForRuleApply(xpr.deepCopy(), newNode());
assertEquals(1, report.getViolations().size());
});
assertEquals("", log); // no additional warnings
// with another rule on the same node, new warnings
XPathRule otherRule = makeRule(version, "OtherRule");
otherRule.setRuleSetName("rset.xml");
log = SystemLambda.tapSystemErrAndOut(() -> {
Report report = getReportForRuleApply(otherRule, firstNode);
assertEquals(1, report.getViolations().size());
});
assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Size' by XPath rule 'OtherRule' (in ruleset 'rset.xml')"));
assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Name' by XPath rule 'OtherRule' (in ruleset 'rset.xml'), please use @Image instead"));
}
XPathRule makeRule(XPathVersion version, String name) {
XPathRule xpr = new XPathRule(version, "//dummyNode[@Size >= 2 and @Name='foo']");
xpr.setName(name);
setDummyLanguage(xpr);
xpr.setMessage("gotcha");
return xpr;
}
XPathRule makeXPath(String xpathExpr) {
XPathRule xpr = new XPathRule(XPathVersion.XPATH_2_0, xpathExpr);
setDummyLanguage(xpr);
xpr.setName("name");
xpr.setMessage("gotcha");
return xpr;
}
@Test
void testFileNameInXpath() {
Report report = executeRule(makeXPath("//*[pmd:fileName() = 'Foo.cls']"),
newRoot("src/Foo.cls"));
assertThat(report.getViolations(), hasSize(1));
}
@Test
void testBeginLine() {
Report report = executeRule(makeXPath("//*[pmd:startLine(.)=1]"),
newRoot("src/Foo.cls"));
assertThat(report.getViolations(), hasSize(1));
}
@Test
void testBeginCol() {
Report report = executeRule(makeXPath("//*[pmd:startColumn(.)=1]"),
newRoot("src/Foo.cls"));
assertThat(report.getViolations(), hasSize(1));
}
@Test
void testEndLine() {
Report report = executeRule(makeXPath("//*[pmd:endLine(.)=1]"),
newRoot("src/Foo.cls"));
assertThat(report.getViolations(), hasSize(1));
}
@Test
void testEndColumn() {
Report report = executeRule(makeXPath("//*[pmd:endColumn(.)>1]"),
newRoot("src/Foo.cls"));
assertThat(report.getViolations(), hasSize(1));
}
Report executeRule(net.sourceforge.pmd.Rule rule, DummyNode node) {
return getReportForRuleApply(rule, node);
}
DummyRootNode newNode() {
DummyRootNode root = newRoot("file");
DummyNode dummy = new DummyNodeWithDeprecatedAttribute();
root.addChild(dummy, 0);
dummy.setRegion(TextRegion.fromOffsetLength(0, 1));
return root;
}
public DummyRootNode newRoot(String fileName) {
return helper.parse("dummy code", fileName);
}
}
| 5,621 | 34.1375 | 175 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/MockRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* This is a Rule implementation which can be used in scenarios where an actual
* functional Rule is not needed. For example, during unit testing, or as an
* editable surrogate used by IDE plugins. The Language of this Rule defaults to
* Java.
*/
public class MockRule extends AbstractRule {
public MockRule() {
super();
definePropertyDescriptor(PropertyFactory.intProperty("testIntProperty").desc("testIntProperty").require(inRange(1, 100)).defaultValue(1).build());
}
public MockRule(String name, String description, String message, String ruleSetName, RulePriority priority) {
this(name, description, message, ruleSetName);
setPriority(priority);
}
public MockRule(String name, String description, String message, String ruleSetName) {
this();
setName(name);
setDescription(description);
setMessage(message);
setRuleSetName(ruleSetName);
}
@Override
public void apply(Node node, RuleContext ctx) {
// the mock rule does nothing. Usually you would start here to analyze the AST.
}
}
| 1,507 | 31.782609 | 154 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/xpath/NoAttributeTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.NoAttribute.NoAttrScope;
import net.sourceforge.pmd.lang.rule.xpath.impl.AttributeAxisIterator;
import net.sourceforge.pmd.util.IteratorUtil;
/**
* @author Clément Fournier
*/
class NoAttributeTest {
@Test
void testNoAttrInherited() {
Node child = new NodeNoInherited();
Set<String> attrNames = IteratorUtil.toList(child.getXPathAttributesIterator()).stream().map(Attribute::getName).collect(Collectors.toSet());
assertTrue(attrNames.contains("SomeInt"));
assertTrue(attrNames.contains("Child"));
// from Node
assertTrue(attrNames.contains("BeginLine"));
assertFalse(attrNames.contains("SomeLong"));
assertFalse(attrNames.contains("Image"));
assertFalse(attrNames.contains("SomeName"));
}
@Test
void testNoAttrAll() {
assertTrue(0 < IteratorUtil.count(new NodeAllAttr(12).getXPathAttributesIterator()));
NodeNoAttrAll child = new NodeNoAttrAll();
Set<String> attrNames = IteratorUtil.toList(child.getXPathAttributesIterator()).stream().map(Attribute::getName).collect(Collectors.toSet());
// from Noded, so not suppressed
assertTrue(attrNames.contains("Image"));
assertFalse(attrNames.contains("MySuppressedAttr"));
}
@Test
void testNoAttrAllIsNotInherited() {
NodeNoAttrAllChild child = new NodeNoAttrAllChild();
Set<String> attrNames = IteratorUtil.toList(child.getXPathAttributesIterator()).stream().map(Attribute::getName).collect(Collectors.toSet());
// suppressed because the parent has NoAttribute(scope = ALL)
assertFalse(attrNames.contains("MySuppressedAttr"));
// not suppressed because defined in the class, which has no annotation
assertTrue(attrNames.contains("NotSuppressedAttr"));
}
private static class DummyNodeParent extends DummyNode {
DummyNodeParent() {
super();
}
public String getSomeName() {
return "Foo";
}
public int getSomeInt() {
return 42;
}
public long getSomeLong() {
return 42;
}
public long getSomeLong2() {
return 42;
}
@Override
public Iterator<Attribute> getXPathAttributesIterator() {
return new AttributeAxisIterator(this);
}
}
@NoAttribute(scope = NoAttrScope.INHERITED)
public static class NodeNoInherited extends DummyNodeParent {
// getSomeName is inherited and filtered out by NoAttrScope.INHERITED
// getSomeInt is inherited but overridden here, so NoAttrScope.INHERITED has no effect
// getSomeLong is inherited and overridden here,
// and even with scope INHERITED its @NoAttribute takes precedence
// isChild overrides nothing so with INHERITED it's not filtered out
@Override
public int getSomeInt() {
return 43;
}
@NoAttribute // Notice
@Override
public long getSomeLong() {
return 43;
}
@NoAttribute(scope = NoAttrScope.INHERITED)
@Override
public String getImage() {
return super.getImage();
}
public boolean isChild() {
return true;
}
}
public static class NodeAllAttr extends DummyNodeParent {
NodeAllAttr(int id) {
super();
}
}
@NoAttribute(scope = NoAttrScope.ALL)
public static class NodeNoAttrAll extends DummyNodeParent {
public int getMySuppressedAttr() {
return 12;
}
}
public static class NodeNoAttrAllChild extends NodeNoAttrAll {
public int getNotSuppressedAttr() {
return 12;
}
}
}
| 4,313 | 24.987952 | 149 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/xpath/impl/AttributeAxisIteratorTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.impl;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.xpath.Attribute;
import net.sourceforge.pmd.util.CollectionUtil;
/**
* Unit test for {@link AttributeAxisIterator}
*/
class AttributeAxisIteratorTest {
private static final Set<String> DEFAULT_ATTRS = setOf("BeginColumn", "BeginLine", "Image", "EndColumn", "EndLine");
/**
* Test hasNext and next.
*/
@Test
void testAttributeAxisIterator() {
DummyNode dummyNode = new DummyNode();
AttributeAxisIterator it = new AttributeAxisIterator(dummyNode);
assertEquals(DEFAULT_ATTRS, toMap(it).keySet());
}
@Test
void testAttributeAxisIteratorWithEnum() {
DummyNodeWithEnum dummyNode = new DummyNodeWithEnum();
AttributeAxisIterator it = new AttributeAxisIterator(dummyNode);
Set<String> expected = CollectionUtil.setUnion(DEFAULT_ATTRS, "Enum");
assertEquals(expected, toMap(it).keySet());
}
@Test
void testAttributeAxisIteratorWithList() {
// list attributes are not supported anymore
DummyNodeWithList dummyNode = new DummyNodeWithList();
AttributeAxisIterator it = new AttributeAxisIterator(dummyNode);
assertEquals(DEFAULT_ATTRS, toMap(it).keySet());
}
private Map<String, Attribute> toMap(AttributeAxisIterator it) {
Map<String, Attribute> atts = new HashMap<>();
while (it.hasNext()) {
Attribute attribute = it.next();
atts.put(attribute.getName(), attribute);
}
return atts;
}
public static class DummyNodeWithEnum extends DummyNode {
public enum MyEnum {
FOO, BAR
}
public MyEnum getEnum() {
return MyEnum.FOO;
}
}
public static class DummyNodeWithList extends DummyNode {
public List<String> getList() {
return Arrays.asList("A", "B");
}
public List<Node> getNodeList() {
return Collections.emptyList();
}
}
}
| 2,540 | 25.195876 | 120 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/xpath/internal/SaxonXPathRuleQueryTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.followPath;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.node;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.nodeB;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.root;
import static net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil.tree;
import static org.hamcrest.MatcherAssert.assertThat;
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.HashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sourceforge.pmd.lang.ast.DummyNodeWithListAndEnum;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.rule.xpath.PmdXPathException;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
import net.sourceforge.pmd.lang.rule.xpath.impl.AbstractXPathFunctionDef;
import net.sourceforge.pmd.lang.rule.xpath.impl.XPathHandler;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.BooleanValue;
import net.sf.saxon.value.SequenceType;
class SaxonXPathRuleQueryTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
// Unsupported: https://github.com/pmd/pmd/issues/2451
// @Test
// void testListAttribute() {
// RootNode dummy = new DummyNodeWithListAndEnum();
//
// assertQuery(1, "//dummyNode[@List = \"A\"]", dummy);
// assertQuery(1, "//dummyNode[@List = \"B\"]", dummy);
// assertQuery(0, "//dummyNode[@List = \"C\"]", dummy);
// assertQuery(1, "//dummyNode[@Enum = \"FOO\"]", dummy);
// assertQuery(0, "//dummyNode[@Enum = \"BAR\"]", dummy);
// assertQuery(1, "//dummyNode[@EnumList = \"FOO\"]", dummy);
// assertQuery(1, "//dummyNode[@EnumList = \"BAR\"]", dummy);
// assertQuery(1, "//dummyNode[@EnumList = (\"FOO\", \"BAR\")]", dummy);
// assertQuery(0, "//dummyNode[@EmptyList = (\"A\")]", dummy);
// }
@Test
void testHigherOrderFuns() { // XPath 3.1
DummyRootNode tree = helper.parse("(oha)");
assertQuery(1, "//dummyRootNode["
+ "(@Image => substring-after('[') => substring-before(']')) "
// -------------------- ---------------------
// Those are higher order functions,
// the arrow operator applies it to the left expression
+ "! . = '']", tree);
// ^ This is the mapping operator, it applies a function on
// the right to every element of the sequence on the left
// Together this says,
// for r in dummyRootNode:
// tmp = atomize(r/@Image)
// tmp = substring-after('[', tmp)
// tmp = substring-before(']', tmp)
// if tmp == '':
// yield r
}
@Test
void testListProperty() {
RootNode dummy = new DummyNodeWithListAndEnum();
PropertyDescriptor<List<String>> prop = PropertyFactory.stringListProperty("prop")
.defaultValues("FOO", "BAR")
.desc("description").build();
assertQuery(1, "//dummyRootNode[@Enum = $prop]", dummy, prop);
}
@Test
void testInvalidReturn() {
DummyNodeWithListAndEnum dummy = new DummyNodeWithListAndEnum();
PmdXPathException exception = assertThrows(PmdXPathException.class, () -> {
createQuery("1+2").evaluate(dummy);
});
assertThat(exception.getMessage(), CoreMatchers.containsString("XPath rule expression returned a non-node"));
assertThat(exception.getMessage(), CoreMatchers.containsString("Int64Value"));
}
@Test
void testRootExpression() {
DummyRootNode dummy = helper.parse("(oha)");
List<Node> result = assertQuery(1, "/", dummy);
assertEquals(dummy, result.get(0));
}
@Test
void testRootExpressionIsADocumentNode() {
DummyRootNode dummy = helper.parse("(oha)");
List<Node> result = assertQuery(1, "(/)[self::document-node()]", dummy);
assertEquals(dummy, result.get(0));
}
@Test
void testRootExpressionWithName() {
DummyRootNode dummy = helper.parse("(oha)");
String xpathName = dummy.getXPathNodeName();
List<Node> result = assertQuery(1, "(/)[self::document-node(element(" + xpathName + "))]", dummy);
assertEquals(dummy, result.get(0));
assertQuery(0, "(/)[self::document-node(element(DummyNodeX))]", dummy);
}
@Test
void ruleChainVisits() {
SaxonXPathRuleQuery query = createQuery("//dummyNode[@Image='baz']/foo | //bar[@Public = 'true'] | //dummyNode[@Public = false()] | //dummyNode");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(2, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertTrue(ruleChainVisits.contains("bar"));
assertEquals(3, query.nodeNameToXPaths.size());
assertExpression("(self::node()[(string(data(@Image))) eq \"baz\"])/child::element(foo)", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("self::node()[(boolean(data(@Public))) eq false()]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(1));
assertExpression("self::node()", query.getExpressionsForLocalNameOrDefault("dummyNode").get(2));
assertExpression("self::node()[(string(data(@Public))) eq \"true\"]", query.getExpressionsForLocalNameOrDefault("bar").get(0));
assertExpression("(((docOrder((((/)/descendant::element(dummyNode))[(string(data(@Image))) eq \"baz\"])/child::element(foo))) | (((/)/descendant::element(bar))[(string(data(@Public))) eq \"true\"])) | (((/)/descendant::element(dummyNode))[(boolean(data(@Public))) eq false()])) | ((/)/descendant::element(dummyNode))", query.getFallbackExpr());
}
@Test
void ruleChainVisitsMultipleFilters() {
SaxonXPathRuleQuery query = createQuery("//dummyNode[@Test1 = false()][@Test2 = true()]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("(self::node()[(boolean(data(@Test1))) eq false()])[(boolean(data(@Test2))) eq true()]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("(((/)/descendant::element(dummyNode))[(boolean(data(@Test1))) eq false()])[(boolean(data(@Test2))) eq true()]", query.getFallbackExpr());
}
@Test
void ruleChainVisitsCustomFunctions() {
SaxonXPathRuleQuery query = createQuery("//dummyNode[pmd-dummy:imageIs(@Image)]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("self::node()[Q{http://pmd.sourceforge.net/pmd-dummy}imageIs(exactly-one(convertUntyped(data(@Image))))]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("((/)/descendant::element(Q{}dummyNode))[Q{http://pmd.sourceforge.net/pmd-dummy}imageIs(exactly-one(convertUntyped(data(@Image))))]", query.getFallbackExpr());
}
/**
* If a query contains another unbounded path expression other than the first one, it must be
* excluded from rule chain execution. Saxon itself optimizes this quite good already.
*/
@Test
void ruleChainVisitsUnboundedPathExpressions() {
SaxonXPathRuleQuery query = createQuery("//dummyNode[//ClassOrInterfaceType]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
assertEquals(1, query.nodeNameToXPaths.size());
assertExpression("let $Q{http://saxon.sf.net/generated-variable}v0 := (/)/descendant::element(Q{}ClassOrInterfaceType) return (((/)/descendant::element(Q{}dummyNode))[exists($Q{http://saxon.sf.net/generated-variable}v0)])", query.getFallbackExpr());
// second sample, more complex
query = createQuery("//dummyNode[ancestor::ClassOrInterfaceDeclaration[//ClassOrInterfaceType]]");
ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
assertEquals(1, query.nodeNameToXPaths.size());
assertExpression("let $Q{http://saxon.sf.net/generated-variable}v0 := (/)/descendant::element(Q{}ClassOrInterfaceType) return (((/)/descendant::element(Q{}dummyNode))[exists(ancestor::element(Q{}ClassOrInterfaceDeclaration)[exists($Q{http://saxon.sf.net/generated-variable}v0)])])", query.getFallbackExpr());
// third example, with boolean expr
query = createQuery("//dummyNode[//ClassOrInterfaceType or //OtherNode]");
ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
assertEquals(1, query.nodeNameToXPaths.size());
assertExpression("let $Q{http://saxon.sf.net/generated-variable}v0 := (exists((/)/descendant::element(Q{}ClassOrInterfaceType))) or (exists((/)/descendant::element(Q{}OtherNode))) return (((/)/descendant::element(Q{}dummyNode))[$Q{http://saxon.sf.net/generated-variable}v0])", query.getFallbackExpr());
}
@Test
void ruleChainVisitsNested() {
SaxonXPathRuleQuery query = createQuery("//dummyNode/foo/*/bar[@Test = 'false']");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("(((self::node()/child::element(foo))/child::element())/child::element(bar))[(string(data(@Test))) eq \"false\"]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("docOrder(((docOrder((((/)/descendant::element(dummyNode))/child::element(foo))/child::element()))/child::element(bar))[(string(data(@Test))) eq \"false\"])", query.getFallbackExpr());
}
@Test
void ruleChainVisitsNested2() {
SaxonXPathRuleQuery query = createQuery("//dummyNode/foo[@Baz = 'a']/*/bar[@Test = 'false']");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("((((self::node()/child::element(foo))[(string(data(@Baz))) eq \"a\"])/child::element())/child::element(bar))[(string(data(@Test))) eq \"false\"]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("docOrder(((docOrder(((((/)/descendant::element(dummyNode))/child::element(foo))[(string(data(@Baz))) eq \"a\"])/child::element()))/child::element(bar))[(string(data(@Test))) eq \"false\"])", query.getFallbackExpr());
}
@Test
void unionBeforeSlash() {
SaxonXPathRuleQuery query = createQuery("(//dummyNode | //dummyNodeB)/dummyNode[@Image = '10']");
DummyRootNode tree = tree(() -> root(
node(
node()
),
nodeB(
node()
)
));
tree.descendantsOrSelf().forEach(n -> {
List<Node> results = query.evaluate(n);
assertEquals(1, results.size());
assertEquals(followPath(tree, "10"), results.get(0));
});
assertExpression("docOrder((((/)/descendant::(element(dummyNode) | element(dummyNodeB)))/child::element(dummyNode))[(string(data(@Image))) eq \"10\"])", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
}
@Test
void unionBeforeSlashWithFilter() {
SaxonXPathRuleQuery query = createQuery("(//dummyNode[@Image='0'] | //dummyNodeB[@Image='1'])/dummyNode[@Image = '10']");
DummyRootNode tree = tree(() -> root(
node(
node()
),
nodeB(
node()
)
));
assertEquals(0, query.getRuleChainVisits().size());
assertExpression("docOrder((((((/)/descendant::element(dummyNode))[(string(data(@Image))) eq \"0\"]) | (((/)/descendant::element(dummyNodeB))[(string(data(@Image))) eq \"1\"]))/child::element(dummyNode))[(string(data(@Image))) eq \"10\"])", query.getFallbackExpr());
tree.descendantsOrSelf().forEach(n -> {
List<Node> results = query.evaluate(n);
assertEquals(1, results.size());
assertEquals(followPath(tree, "10"), results.get(0));
});
}
@Test
void unionBeforeSlashDeeper() {
SaxonXPathRuleQuery query = createQuery("(//dummyNode | //dummyNodeB)/dummyNode/dummyNode");
DummyRootNode tree = tree(() -> root(
node(
node(
node()
)
),
nodeB(
node()
)
));
assertEquals(0, query.getRuleChainVisits().size());
assertExpression("docOrder((((/)/descendant::(element(dummyNode) | element(dummyNodeB)))/child::element(dummyNode))/child::element(dummyNode))", query.getFallbackExpr());
tree.descendantsOrSelf().forEach(n -> {
List<Node> results = query.evaluate(n);
assertEquals(1, results.size());
assertEquals(followPath(tree, "000"), results.get(0));
});
}
@Test
void ruleChainVisitWithVariable() {
PropertyDescriptor<String> testClassPattern = PropertyFactory.stringProperty("testClassPattern").desc("test").defaultValue("a").build();
SaxonXPathRuleQuery query = createQuery("//dummyNode[matches(@SimpleName, $testClassPattern)]", testClassPattern);
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("self::node()[matches(convertUntyped(data(@SimpleName)), \"a\", \"\")]", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("((/)/descendant::element(Q{}dummyNode))[matches(convertUntyped(data(@SimpleName)), \"a\", \"\")]", query.getFallbackExpr());
}
@Test
void ruleChainVisitWithVariable2() {
PropertyDescriptor<String> testClassPattern = PropertyFactory.stringProperty("testClassPattern").desc("test").defaultValue("a").build();
SaxonXPathRuleQuery query = createQuery("//dummyNode[matches(@SimpleName, $testClassPattern)]/foo", testClassPattern);
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("(self::node()[matches(convertUntyped(data(@SimpleName)), \"a\", \"\")])/child::element(Q{}foo)", query.getExpressionsForLocalNameOrDefault("dummyNode").get(0));
assertExpression("docOrder((((/)/descendant::element(Q{}dummyNode))[matches(convertUntyped(data(@SimpleName)), \"a\", \"\")])/child::element(Q{}foo))", query.getFallbackExpr());
}
@Test
void ruleChainVisitWithTwoFunctions() {
SaxonXPathRuleQuery query = createQuery("//dummyNode[ends-with(@Image, 'foo')][pmd-dummy:imageIs('bar')]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(1, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertEquals(2, query.nodeNameToXPaths.size());
assertExpression("let $v0 := imageIs(\"bar\") return ((self::node()[ends-with(convertUntyped(data(@Image)), \"foo\")])[$v0])", query.nodeNameToXPaths.get("dummyNode").get(0));
}
@Test
void ruleChainWithUnions() {
SaxonXPathRuleQuery query = createQuery("(//ForStatement | //WhileStatement | //DoStatement)//AssignmentOperator");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
}
@Test
void ruleChainWithUnionsAndFilter() {
SaxonXPathRuleQuery query = createQuery("(//ForStatement | //WhileStatement | //DoStatement)//AssignmentOperator[@Image='foo']");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
}
@Test
void ruleChainWithUnionsCustomFunctionsVariant1() {
SaxonXPathRuleQuery query = createQuery("(//ForStatement | //WhileStatement | //DoStatement)//dummyNode[pmd-dummy:imageIs(@Image)]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
}
@Test
void ruleChainWithUnionsCustomFunctionsVariant2() {
SaxonXPathRuleQuery query = createQuery("//(ForStatement | WhileStatement | DoStatement)//dummyNode[pmd-dummy:imageIs(@Image)]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(0, ruleChainVisits.size());
}
@Test
void ruleChainWithUnionsCustomFunctionsVariant3() {
SaxonXPathRuleQuery query = createQuery("//ForStatement//dummyNode[pmd-dummy:imageIs(@Image)]"
+ " | //WhileStatement//dummyNode[pmd-dummy:imageIs(@Image)]"
+ " | //DoStatement//dummyNode[pmd-dummy:imageIs(@Image)]");
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(3, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("ForStatement"));
assertTrue(ruleChainVisits.contains("WhileStatement"));
assertTrue(ruleChainVisits.contains("DoStatement"));
final String expectedSubexpression = "(self::node()/descendant::element(dummyNode))[imageIs(exactly-one(convertUntyped(data(@Image))))]";
assertExpression(expectedSubexpression, query.nodeNameToXPaths.get("ForStatement").get(0));
assertExpression(expectedSubexpression, query.nodeNameToXPaths.get("WhileStatement").get(0));
assertExpression(expectedSubexpression, query.nodeNameToXPaths.get("DoStatement").get(0));
}
@Test
void ruleChainVisitsWithUnionsAndLets() {
PropertyDescriptor<Boolean> boolProperty = PropertyFactory.booleanProperty("checkAll").desc("test").defaultValue(true).build();
SaxonXPathRuleQuery query = createQuery("//dummyNode[$checkAll and ClassOrInterfaceType] | //ForStatement[not($checkAll)]", boolProperty);
List<String> ruleChainVisits = query.getRuleChainVisits();
assertEquals(2, ruleChainVisits.size());
assertTrue(ruleChainVisits.contains("dummyNode"));
assertTrue(ruleChainVisits.contains("ForStatement"));
}
private static void assertExpression(String expected, Expression actual) {
assertEquals(normalizeExprDump(expected),
normalizeExprDump(actual.toString()));
}
private static String normalizeExprDump(String dump) {
return dump.replaceAll("Q\\{[^}]*+}", "") // remove namespaces
// generated variable ids
.replaceAll("\\$qq:qq-?\\d+", "\\$qq:qq000")
.replaceAll("\\$zz:zz-?\\d+", "\\$zz:zz000");
}
private static List<Node> assertQuery(int resultSize, String xpath, Node node, PropertyDescriptor<?>... descriptors) {
SaxonXPathRuleQuery query = createQuery(xpath, descriptors);
List<Node> result = query.evaluate(node);
assertEquals(resultSize, result.size(), "Wrong number of matched nodes");
return result;
}
private static SaxonXPathRuleQuery createQuery(String xpath, PropertyDescriptor<?>... descriptors) {
Map<PropertyDescriptor<?>, Object> props = new HashMap<>();
if (descriptors != null) {
for (PropertyDescriptor<?> prop : descriptors) {
props.put(prop, prop.defaultValue());
}
}
return new SaxonXPathRuleQuery(
xpath,
XPathVersion.DEFAULT,
props,
XPathHandler.getHandlerForFunctionDefs(imageIsFunction()),
DeprecatedAttrLogger.noop()
);
}
@NonNull
private static AbstractXPathFunctionDef imageIsFunction() {
return new AbstractXPathFunctionDef("imageIs", "dummy") {
@Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[] {SequenceType.SINGLE_STRING};
}
@Override
public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) {
return SequenceType.SINGLE_BOOLEAN;
}
@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@Override
public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {
Node contextNode = ((AstElementNode) context.getContextItem()).getUnderlyingNode();
return BooleanValue.get(arguments[0].head().getStringValue().equals(contextNode.getImage()));
}
};
}
};
}
}
| 22,486 | 49.082405 | 352 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/xpath/internal/ElementNodeTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.xpath.internal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import net.sourceforge.pmd.DummyParsingHelper;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
import net.sf.saxon.Configuration;
import net.sf.saxon.type.Type;
class ElementNodeTest {
@RegisterExtension
private final DummyParsingHelper helper = new DummyParsingHelper();
@Test
void testCompareOrder() {
DummyRootNode root = helper.parse(
"(#foo)"
+ "(#foo)"
);
DummyNode c0 = root.getChild(0);
DummyNode c1 = root.getChild(1);
Configuration configuration = Configuration.newConfiguration();
AstTreeInfo treeInfo = new AstTreeInfo(root, configuration);
assertSame(root, treeInfo.getRootNode().getUnderlyingNode());
assertEquals(Type.DOCUMENT, treeInfo.getRootNode().getNodeKind());
AstElementNode rootElt = treeInfo.getRootNode().getRootElement();
assertSame(root, rootElt.getUnderlyingNode());
assertEquals(Type.ELEMENT, rootElt.getNodeKind());
assertSame(rootElt, treeInfo.findWrapperFor(root));
AstElementNode elementFoo0 = rootElt.getChildren().get(0);
assertSame(c0, elementFoo0.getUnderlyingNode());
assertSame(elementFoo0, treeInfo.findWrapperFor(c0));
AstElementNode elementFoo1 = rootElt.getChildren().get(1);
assertSame(c1, elementFoo1.getUnderlyingNode());
assertSame(elementFoo1, treeInfo.findWrapperFor(c1));
assertFalse(elementFoo0.isSameNodeInfo(elementFoo1));
assertFalse(elementFoo1.isSameNodeInfo(elementFoo0));
assertTrue(elementFoo0.compareOrder(elementFoo1) < 0);
assertTrue(elementFoo1.compareOrder(elementFoo0) > 0);
assertEquals(0, elementFoo0.compareOrder(elementFoo0));
assertEquals(0, elementFoo1.compareOrder(elementFoo1));
}
@Test
void verifyTextNodeType() {
DummyRootNode root = helper.parse("(foo)(#text)");
DummyNode c0 = root.getChild(0);
DummyNode c1 = root.getChild(1);
Configuration configuration = Configuration.newConfiguration();
AstTreeInfo treeInfo = new AstTreeInfo(root, configuration);
AstElementNode rootElt = treeInfo.getRootNode().getRootElement();
assertSame(root, rootElt.getUnderlyingNode());
assertEquals(Type.ELEMENT, rootElt.getNodeKind());
assertSame(rootElt, treeInfo.findWrapperFor(root));
AstElementNode elementFoo0 = rootElt.getChildren().get(0);
assertEquals(Type.ELEMENT, elementFoo0.getNodeKind());
assertSame(c0, elementFoo0.getUnderlyingNode());
assertSame(elementFoo0, treeInfo.findWrapperFor(c0));
AstElementNode elementText1 = rootElt.getChildren().get(1);
assertEquals(Type.TEXT, elementText1.getNodeKind());
assertSame(c1, elementText1.getUnderlyingNode());
assertSame(elementText1, treeInfo.findWrapperFor(c1));
}
@Test
void verifyCommentNodeType() {
DummyRootNode root = helper.parse("(#comment)");
DummyNode c1 = root.getChild(0);
Configuration configuration = Configuration.newConfiguration();
AstTreeInfo treeInfo = new AstTreeInfo(root, configuration);
AstElementNode rootElt = treeInfo.getRootNode().getRootElement();
AstElementNode elementComment = rootElt.getChildren().get(0);
assertEquals("#comment", c1.getXPathNodeName());
assertEquals(Type.COMMENT, elementComment.getNodeKind());
assertSame(c1, elementComment.getUnderlyingNode());
assertSame(elementComment, treeInfo.findWrapperFor(c1));
}
}
| 4,117 | 36.099099 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/internal/LatticeRelationTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.rule.internal;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import org.pcollections.HashTreePSet;
import org.pcollections.PSet;
import net.sourceforge.pmd.internal.util.PredicateUtil;
class LatticeRelationTest {
@Test
void testCustomTopo() {
LatticeRelation<Set<Integer>, String, Set<String>> lattice = setLattice(PredicateUtil.always());
lattice.put(setOf(1, 2, 3), "123");
lattice.put(setOf(4), "4");
lattice.put(setOf(4, 3), "43");
// http://bit.ly/39J3KOu
assertEquals(setOf("123"), lattice.get(setOf(1, 2, 3)));
assertEquals(setOf("4", "43"), lattice.get(setOf(4)));
assertEquals(setOf("43", "123"), lattice.get(setOf(3)));
assertEquals(setOf("43", "123", "4"), lattice.get(emptySet()));
assertEquals(emptySet(), lattice.get(setOf(5)));
}
@Test
void testClearing() {
LatticeRelation<Set<Integer>, String, Set<String>> lattice = setLattice(PredicateUtil.always());
lattice.put(setOf(1, 2), "12");
lattice.put(setOf(1), "1");
lattice.put(setOf(3), "3");
assertEquals(setOf("12"), lattice.get(setOf(2)));
assertEquals(setOf("12", "1"), lattice.get(setOf(1)));
assertEquals(setOf("12"), lattice.get(setOf(1, 2)));
assertEquals(setOf("3"), lattice.get(setOf(3)));
assertEquals(emptySet(), lattice.get(setOf(5)));
assertEquals(setOf("1", "12", "3"), lattice.get(emptySet()));
lattice.clearValues();
assertEquals(emptySet(), lattice.get(setOf(2)));
assertEquals(emptySet(), lattice.get(setOf(1)));
assertEquals(emptySet(), lattice.get(setOf(1, 2)));
assertEquals(emptySet(), lattice.get(setOf(3)));
assertEquals(emptySet(), lattice.get(setOf(5)));
assertEquals(emptySet(), lattice.get(emptySet()));
}
@Test
void testTopoFilter() {
// filter out sets with size 2
// this cuts out one level of the graph
// goal of the test is to ensure, that their predecessors (sets with size > 2)
// are still connected to successors (size < 2)
LatticeRelation<Set<Integer>, String, Set<String>> lattice = setLattice(it -> it.size() != 2);
lattice.put(setOf(1, 2, 3), "123");
lattice.put(setOf(4), "4");
lattice.put(setOf(4, 3), "43");
lattice.put(setOf(4, 3, 5), "435");
// before filter:
// http://bit.ly/38vRsce
// after filter:
// http://bit.ly/2SxejyC
assertEquals(setOf("123"), lattice.get(setOf(1, 2, 3)));
assertEquals(setOf("4", "43", "435"), lattice.get(setOf(4)));
assertEquals(setOf("123", "43", "435"), lattice.get(setOf(3)));
assertEquals(setOf("123", "4", "43", "435"), lattice.get(emptySet()));
lattice.put(setOf(4, 3, 6), "436");
assertEquals(setOf("4", "43", "435", "436"), lattice.get(setOf(4)));
}
@Test
void testInitialSetFilter() {
LatticeRelation<Set<Integer>, String, Set<String>> lattice =
new LatticeRelation<>(
setTopoOrder(),
setOf(setOf(1, 2), setOf(1, 2, 3), setOf(2, 3), emptySet()),
Objects::toString,
Collectors.toSet()
);
lattice.put(setOf(1, 2, 3), "123");
lattice.put(setOf(1, 2), "12");
lattice.put(setOf(1), "1");
lattice.put(setOf(2, 3, 4), "234");
lattice.put(setOf(4, 3, 5, 6), "435");
assertEquals(setOf("123"), lattice.get(setOf(1, 2, 3)));
assertEquals(setOf("12", "123"), lattice.get(setOf(1, 2)));
assertEquals(setOf("123", "234"), lattice.get(setOf(2, 3)));
assertEquals(setOf("1", "12", "123", "234", "435"), lattice.get(emptySet()));
assertEquals(emptySet(), lattice.get(setOf(4))); // not in initial set
assertEquals(emptySet(), lattice.get(setOf(4, 5))); // not in initial set
assertEquals(emptySet(), lattice.get(setOf(2, 3, 4))); // not in initial set
lattice.put(setOf(2, 3, 4), "234*");
assertEquals(setOf("123", "234", "234*"), lattice.get(setOf(2, 3))); // value "43" has been pruned
}
@Test
void testDiamond() {
LatticeRelation<Set<Integer>, String, Set<String>> lattice = setLattice(PredicateUtil.always());
lattice.put(setOf(1, 2), "12");
// We have
// {1,2}
// / \
// {1} {2}
// \ /
// { }
// Goal is to assert, that when we ask first for the value of { },
// the value of every node is correctly computed, even if they're
// reachable from several paths
assertEquals(setOf("12"), lattice.get(emptySet()));
assertEquals(setOf("12"), lattice.get(setOf(1)));
assertEquals(setOf("12"), lattice.get(setOf(2)));
assertEquals(setOf("12"), lattice.get(setOf(1, 2)));
}
@Test
void testFilterOnChainSetup() {
// setup for the next test (difference here is no filter)
LatticeRelation<String, String, Set<String>> lattice = stringLattice(PredicateUtil.always());
lattice.put("abc", "val");
// We have "abc" <: "bc" <: "c" <: ""
assertEquals(setOf("val"), lattice.get(""));
assertEquals(setOf("val"), lattice.get("abc"));
assertEquals(setOf("val"), lattice.get("bc"));
assertEquals(setOf("val"), lattice.get("c"));
assertEquals(emptySet(), lattice.get("d"));
}
@Test
void testFilterOnChain() {
LatticeRelation<String, String, Set<String>> lattice = stringLattice(s -> s.length() != 2 && s.length() != 1);
lattice.put("abc", "val");
// We have "abc" <: "bc" <: "c" <: ""
// We filter out both "bc" and "c"
// "abc" should still be connected to ""
assertEquals(setOf("val"), lattice.get(""));
assertEquals(setOf("val"), lattice.get("abc"));
assertEquals(emptySet(), lattice.get("bc"));
assertEquals(emptySet(), lattice.get("c"));
assertEquals(emptySet(), lattice.get("d"));
}
@Test
void testTransitiveSucc() {
LatticeRelation<String, String, Set<String>> lattice =
stringLattice(s -> s.equals("c") || s.equals("bc"));
lattice.put("abc", "val");
lattice.put("bc", "v2");
// We have "abc" <: "bc" <: "c" <: ""
assertEquals(emptySet(), lattice.transitiveQuerySuccs(""));
assertEquals(emptySet(), lattice.get(""));
assertEquals(setOf("c", "bc"), lattice.transitiveQuerySuccs("abc"));
assertEquals(emptySet(), lattice.get("abc"));
assertEquals(setOf("c"), lattice.transitiveQuerySuccs("bc"));
assertEquals(setOf("val", "v2"), lattice.get("bc"));
assertEquals(emptySet(), lattice.transitiveQuerySuccs("c"));
assertEquals(setOf("val", "v2"), lattice.get("c"));
assertEquals(emptySet(), lattice.transitiveQuerySuccs("d"));
assertEquals(emptySet(), lattice.get("d"));
}
@Test
void testTransitiveSuccWithHoleInTheMiddle() {
LatticeRelation<String, String, Set<String>> lattice =
stringLattice(setOf("abc", "bbc", "c")::contains);
lattice.put("abc", "v1");
lattice.put("bbc", "v2");
// We have "abc" <: "bc" <: "c" <: ""
// We have "bbc" <: "bc" <: "c" <: ""
// Only "abc", "bbc" and "c" are query nodes
// When adding "abc" we add its successors and link "abc" to "c"
// When adding "bbc" it must be linked to "c" even if on its
// path to "c" there is "bc", which is not a QNode and was already added
assertEquals(emptySet(), lattice.transitiveQuerySuccs(""));
assertEquals(emptySet(), lattice.get(""));
assertEquals(setOf("c"), lattice.transitiveQuerySuccs("abc"));
assertEquals(setOf("v1"), lattice.get("abc"));
assertEquals(setOf("c"), lattice.transitiveQuerySuccs("bbc"));
assertEquals(setOf("v2"), lattice.get("bbc"));
assertEquals(emptySet(), lattice.get("bc"));
assertEquals(emptySet(), lattice.transitiveQuerySuccs("c"));
assertEquals(setOf("v1", "v2"), lattice.get("c"));
}
@Test
void testToString() {
LatticeRelation<Set<Integer>, String, Set<String>> lattice = setLattice(set -> set.size() < 2);
lattice.put(setOf(1, 2), "12");
// {1,2}
// / \
// {1} {2}
// \ /
// { }
// all {1}, {2}, and { } are query nodes, not {1,2}
assertEquals("strict digraph {\n"
+ "n0 [ shape=box, color=green, label=\"[]\" ];\n"
+ "n1 [ shape=box, color=green, label=\"[1]\" ];\n"
+ "n2 [ shape=box, color=green, label=\"[2]\" ];\n"
+ "n3 [ shape=box, color=black, label=\"[1, 2]\" ];\n"
+ "n1 -> n0;\n" // {1} -> { }
+ "n2 -> n0;\n" // {2} -> { }
+ "n3 -> n0;\n" // {1,2} -> { }
+ "n3 -> n1;\n" // {1,2} -> {1}
+ "n3 -> n2;\n" // {1,2} -> {2}
+ "}", lattice.toString());
}
@Test
void testCycleDetection() {
List<String> cycle = Arrays.asList("a", "b", "c", "d");
TopoOrder<String> cyclicOrder = str -> {
int i = cycle.indexOf(str);
return singletonList(cycle.get((i + 1) % cycle.size()));
};
LatticeRelation<String, String, Set<String>> lattice =
new LatticeRelation<>(cyclicOrder, PredicateUtil.always(), Objects::toString, Collectors.toSet());
IllegalStateException exception = assertThrows(IllegalStateException.class, () -> {
lattice.put("a", "1");
});
assertEquals("Cycle in graph: a -> b -> c -> d -> a", exception.getMessage());
}
@NonNull
private LatticeRelation<String, String, Set<String>> stringLattice(Predicate<String> filter) {
return new LatticeRelation<>(stringTopoOrder(), filter, Objects::toString, Collectors.toSet());
}
@NonNull
private LatticeRelation<Set<Integer>, String, Set<String>> setLattice(Predicate<Set<Integer>> filter) {
return new LatticeRelation<>(setTopoOrder(), filter, Objects::toString, Collectors.toSet());
}
/**
* Direct successors of a set are all the sets that have exactly
* one less element. For example:
* <pre>{@code
*
* {1, 2, 3} <: {1, 2}, {1, 3}, {2, 3}
* {2, 3} <: {2}, {3}
* {2} <: {}
* etc
*
* }</pre>
*
* See eg http://bit.ly/31Xve0v
*/
private static <T> TopoOrder<Set<T>> setTopoOrder() {
return node -> {
Set<Set<T>> successors = new HashSet<>();
for (T s : node) {
PSet<T> minus = HashTreePSet.<T>empty().plusAll(node).minus(s);
successors.add(minus);
}
return successors;
};
}
/**
* Generates a linear topo order according to suffix order. This
* can never form diamonds, as any string has at most one successor.
* Eg
* <pre>{@code
* "abc" <: "bc" <: "c" <: ""
* }</pre>
*/
private static TopoOrder<String> stringTopoOrder() {
return str -> str.isEmpty() ? emptyList()
: singletonList(str.substring(1));
}
}
| 12,199 | 32.333333 | 118 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/symboltable/ApplierTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.symboltable;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
class ApplierTest {
private static class MyFunction implements Predicate<Object> {
private int numCallbacks = 0;
private final int maxCallbacks;
MyFunction(int maxCallbacks) {
this.maxCallbacks = maxCallbacks;
}
@Override
public boolean test(Object o) {
this.numCallbacks++;
return numCallbacks < maxCallbacks;
}
public int getNumCallbacks() {
return this.numCallbacks;
}
}
@Test
void testSimple() {
MyFunction f = new MyFunction(Integer.MAX_VALUE);
List<Object> l = new ArrayList<>();
l.add(new Object());
l.add(new Object());
l.add(new Object());
Applier.apply(f, l.iterator());
assertEquals(l.size(), f.getNumCallbacks());
}
@Test
void testLimit() {
MyFunction f = new MyFunction(2);
List<Object> l = new ArrayList<>();
l.add(new Object());
l.add(new Object());
l.add(new Object());
Applier.apply(f, l.iterator());
assertEquals(2, f.getNumCallbacks());
}
}
| 1,453 | 24.068966 | 79 | java |
pmd | pmd-master/pmd-core/src/test/java/net/sourceforge/pmd/lang/impl/MultiThreadProcessorTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.impl;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.Report.GlobalReportBuilderListener;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextFile;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.reporting.FileAnalysisListener;
import net.sourceforge.pmd.reporting.GlobalAnalysisListener;
class MultiThreadProcessorTest {
private SimpleReportListener reportListener;
PmdAnalysis setupForTest(final String ruleset) {
PMDConfiguration configuration = new PMDConfiguration();
configuration.setThreads(2);
configuration.setIgnoreIncrementalAnalysis(true);
PmdAnalysis pmd = PmdAnalysis.create(configuration);
LanguageVersion lv = DummyLanguageModule.getInstance().getDefaultVersion();
pmd.files().addFile(TextFile.forCharSeq("abc", FileId.fromPathLikeString("file1-violation.dummy"), lv));
pmd.files().addFile(TextFile.forCharSeq("DEF", FileId.fromPathLikeString("file2-foo.dummy"), lv));
reportListener = new SimpleReportListener();
GlobalAnalysisListener listener = GlobalAnalysisListener.tee(listOf(
new GlobalReportBuilderListener(),
reportListener
));
pmd.addListener(listener);
pmd.addRuleSet(pmd.newRuleSetLoader().loadFromResource(ruleset));
return pmd;
}
// TODO: Dysfunctional rules are pruned upstream of the processor.
//
// @Test
// void testRulesDysnfunctionalLog() throws Exception {
// RuleSets ruleSets = setUpForTest("rulesets/MultiThreadProcessorTest/dysfunctional.xml");
// final SimpleRenderer renderer = new SimpleRenderer(null, null);
// renderer.start();
// processor.processFiles(ruleSets, files, listener);
// renderer.end();
//
// final Iterator<ConfigurationError> configErrors = renderer.getReport().getConfigurationErrors().iterator();
// final ConfigurationError error = configErrors.next();
//
// assertEquals("Dysfunctional rule message not present",
// DysfunctionalRule.DYSFUNCTIONAL_RULE_REASON, error.issue());
// assertEquals("Dysfunctional rule is wrong",
// DysfunctionalRule.class, error.rule().getClass());
// assertFalse("More configuration errors found than expected", configErrors.hasNext());
// }
@Test
void testRulesThreadSafety() throws Exception {
try (PmdAnalysis pmd = setupForTest("rulesets/MultiThreadProcessorTest/basic.xml")) {
pmd.performAnalysis();
}
// if the rule is not executed, then maybe a
// ConcurrentModificationException happened
assertEquals(2, NotThreadSafeRule.count.get(), "Test rule has not been executed");
// if the violation is not reported, then the rule instances have been
// shared between the threads
assertEquals(1, reportListener.violations.get(), "Missing violation");
}
public static class NotThreadSafeRule extends AbstractRule {
public static AtomicInteger count = new AtomicInteger(0);
private boolean hasViolation; // this variable will be overridden
// between the threads
@Override
public void apply(Node target, RuleContext ctx) {
count.incrementAndGet();
if (target.getTextDocument().getFileId().getOriginalPath().contains("violation")) {
hasViolation = true;
} else {
letTheOtherThreadRun(10);
hasViolation = false;
}
letTheOtherThreadRun(100);
if (hasViolation) {
addViolation(ctx, target);
}
}
private void letTheOtherThreadRun(int millis) {
try {
Thread.yield();
Thread.sleep(millis);
} catch (InterruptedException e) {
// ignored
}
}
}
public static class DysfunctionalRule extends AbstractRule {
public static final String DYSFUNCTIONAL_RULE_REASON = "dysfunctional rule is dysfunctional";
@Override
public void apply(Node target, RuleContext ctx) {
// noop
}
@Override
public String dysfunctionReason() {
return DYSFUNCTIONAL_RULE_REASON;
}
}
private static class SimpleReportListener implements GlobalAnalysisListener {
public AtomicInteger violations = new AtomicInteger(0);
@Override
public FileAnalysisListener startFileAnalysis(TextFile file) {
return new FileAnalysisListener() {
@Override
public void onRuleViolation(RuleViolation violation) {
violations.incrementAndGet();
}
};
}
@Override
public void close() throws Exception {
}
}
}
| 5,625 | 35.771242 | 121 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.