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-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftErrorNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.Token;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrErrorNode;
public final class SwiftErrorNode extends BaseAntlrErrorNode<SwiftNode> implements SwiftNode {
SwiftErrorNode(Token token) {
super(token);
}
}
| 399 | 21.222222 | 94 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/rule/bestpractices/UnavailableFunctionRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.rule.bestpractices;
import java.util.List;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.swift.AbstractSwiftRule;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwAttribute;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwAttributes;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwCodeBlock;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwFunctionDeclaration;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwInitializerDeclaration;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwStatement;
import net.sourceforge.pmd.lang.swift.ast.SwiftVisitor;
import net.sourceforge.pmd.lang.swift.ast.SwiftVisitorBase;
public class UnavailableFunctionRule extends AbstractSwiftRule {
private static final String AVAILABLE_UNAVAILABLE = "@available(*,unavailable)";
private static final String FATAL_ERROR = "fatalError";
public UnavailableFunctionRule() {
super();
addRuleChainVisit(SwFunctionDeclaration.class);
addRuleChainVisit(SwInitializerDeclaration.class);
}
@Override
public SwiftVisitor<RuleContext, ?> buildVisitor() {
return new SwiftVisitorBase<RuleContext, Void>() {
@Override
public Void visitFunctionDeclaration(final SwFunctionDeclaration ctx, RuleContext ruleCtx) {
if (ctx == null) {
return null;
}
if (shouldIncludeUnavailableModifier(ctx.functionBody().codeBlock())) {
final SwAttributes attributes = ctx.functionHead().attributes();
if (attributes == null || !hasUnavailableModifier(attributes.attribute())) {
addViolation(ruleCtx, ctx);
}
}
return null;
}
@Override
public Void visitInitializerDeclaration(final SwInitializerDeclaration ctx, RuleContext ruleCtx) {
if (ctx == null) {
return null;
}
if (shouldIncludeUnavailableModifier(ctx.initializerBody().codeBlock())) {
final SwAttributes attributes = ctx.initializerHead().attributes();
if (attributes == null || !hasUnavailableModifier(attributes.attribute())) {
addViolation(ruleCtx, ctx);
}
}
return null;
}
private boolean shouldIncludeUnavailableModifier(final SwCodeBlock ctx) {
if (ctx == null || ctx.statements() == null) {
return false;
}
final List<SwStatement> statements = ctx.statements().statement();
return statements.size() == 1 && FATAL_ERROR.equals(statements.get(0).getFirstAntlrToken().getText());
}
private boolean hasUnavailableModifier(final List<SwAttribute> attributes) {
return attributes.stream().anyMatch(atr -> AVAILABLE_UNAVAILABLE.equals(atr.joinTokenText()));
}
};
}
}
| 3,242 | 37.607143 | 118 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/cpd/SwiftTokenizer.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.lang.swift.ast.SwiftLexer;
/**
* SwiftTokenizer
*/
public class SwiftTokenizer extends AntlrTokenizer {
@Override
protected Lexer getLexerForSource(final CharStream charStream) {
return new SwiftLexer(charStream);
}
}
| 520 | 21.652174 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/cpd/SwiftLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.swift.SwiftLanguageModule;
/**
* Language implementation for Swift
*/
public class SwiftLanguage extends AbstractLanguage {
/**
* Creates a new Swift Language instance.
*/
public SwiftLanguage() {
super(SwiftLanguageModule.NAME, SwiftLanguageModule.TERSE_NAME, new SwiftTokenizer(), SwiftLanguageModule.EXTENSIONS);
}
}
| 509 | 23.285714 | 126 | java |
pmd | pmd-master/pmd-lang-test/src/main/java/net/sourceforge/pmd/test/AbstractMetricTestRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.metrics.Metric;
import net.sourceforge.pmd.lang.metrics.MetricOption;
import net.sourceforge.pmd.lang.metrics.MetricOptions;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* Abstract test rule for a metric. Tests of metrics use the standard
* framework for rule testing, using one dummy rule per metric. Default
* parameters can be overridden by overriding the protected methods of
* this class.
*
* @param <N> Result type of the metric. The nested subclasses provide
* defaults for common result types
*
* @author Clément Fournier
*/
public abstract class AbstractMetricTestRule<N extends Number & Comparable<N>> extends AbstractRule {
private final PropertyDescriptor<List<MetricOption>> optionsDescriptor =
PropertyFactory.enumListProperty("metricOptions", optionMappings())
.desc("Choose a variant of the metric or the standard")
.emptyDefaultValue()
.build();
private final PropertyDescriptor<String> reportLevelDescriptor =
PropertyFactory.stringProperty("reportLevel")
.desc("Minimum value required to report")
.defaultValue("" + defaultReportLevel())
.build();
private final Metric<?, N> metric;
public AbstractMetricTestRule(Metric<?, N> metric) {
this.metric = metric;
definePropertyDescriptor(reportLevelDescriptor);
definePropertyDescriptor(optionsDescriptor);
}
protected abstract N parseReportLevel(String value);
protected boolean reportOn(Node node) {
return metric.supports(node);
}
/**
* Mappings of labels to options for use in the options property.
*
* @return A map of labels to options
*/
protected Map<String, MetricOption> optionMappings() {
return new HashMap<>();
}
/**
* Default report level, which is 0.
*
* @return The default report level.
*/
protected abstract N defaultReportLevel();
protected String violationMessage(Node node, N result) {
return MessageFormat.format("At line {0} level {1}", node.getBeginLine(), result);
}
@Override
public void apply(Node target, RuleContext ctx) {
if (reportOn(target)) {
MetricOptions options = MetricOptions.ofOptions(getProperty(optionsDescriptor));
N reportLevel = parseReportLevel(getProperty(reportLevelDescriptor));
N result = Metric.compute(metric, target, options);
if (result != null && reportLevel.compareTo(result) <= 0) {
addViolationWithMessage(ctx, target, violationMessage(target, result));
}
}
// visit the whole tree
for (Node child : target.children()) {
apply(child, ctx);
}
}
public abstract static class OfInt extends AbstractMetricTestRule<Integer> {
protected OfInt(Metric<?, Integer> metric) {
super(metric);
}
@Override
protected Integer parseReportLevel(String value) {
return Integer.parseInt(value);
}
@Override
protected Integer defaultReportLevel() {
return 0;
}
}
public abstract static class OfDouble extends AbstractMetricTestRule<Double> {
protected OfDouble(Metric<?, Double> metric) {
super(metric);
}
@Override
protected Double parseReportLevel(String value) {
return Double.parseDouble(value);
}
@Override
protected Double defaultReportLevel() {
return 0.;
}
}
}
| 4,139 | 29.218978 | 101 | java |
pmd | pmd-master/pmd-tsql/src/test/java/net/sourceforge/pmd/lang/tsql/cpd/TSqlTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.tsql.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class TSqlTokenizerTest extends CpdTextComparisonTest {
TSqlTokenizerTest() {
super(".sql");
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new TSqlTokenizer();
}
@Override
protected String getResourcePrefix() {
return "../cpd/testdata";
}
@Test
void simpleTest() {
doTest("simple");
}
@Test
void mailJobTimeLineTest() {
doTest("MailJobTimeLine");
}
}
| 781 | 18.55 | 79 | java |
pmd | pmd-master/pmd-tsql/src/main/java/net/sourceforge/pmd/lang/tsql/ast/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.tsql.ast;
| 131 | 21 | 79 | java |
pmd | pmd-master/pmd-tsql/src/main/java/net/sourceforge/pmd/lang/tsql/cpd/TSqlLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.tsql.cpd;
import net.sourceforge.pmd.cpd.AbstractLanguage;
/**
* @author pguyot@kallisys.net
*/
public class TSqlLanguage extends AbstractLanguage {
public TSqlLanguage() {
super("TSql", "tsql", new TSqlTokenizer(), ".sql");
}
}
| 372 | 19.722222 | 79 | java |
pmd | pmd-master/pmd-tsql/src/main/java/net/sourceforge/pmd/lang/tsql/cpd/CaseChangingCharStream.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.tsql.cpd;
// Copied from: https://github.com/antlr/antlr4/blob/4.9.1/doc/resources/CaseChangingCharStream.java
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.misc.Interval;
/**
* This class supports case-insensitive lexing by wrapping an existing
* {@link CharStream} and forcing the lexer to see either upper or
* lowercase characters. Grammar literals should then be either upper or
* lower case such as 'BEGIN' or 'begin'. The text of the character
* stream is unaffected. Example: input 'BeGiN' would match lexer rule
* 'BEGIN' if constructor parameter upper=true but getText() would return
* 'BeGiN'.
*/
class CaseChangingCharStream implements CharStream {
final CharStream stream;
final boolean upper;
/**
* Constructs a new CaseChangingCharStream wrapping the given {@link CharStream} forcing
* all characters to upper case or lower case.
* @param stream The stream to wrap.
* @param upper If true force each symbol to upper case, otherwise force to lower.
*/
CaseChangingCharStream(CharStream stream, boolean upper) {
this.stream = stream;
this.upper = upper;
}
@Override
public String getText(Interval interval) {
return stream.getText(interval);
}
@Override
public void consume() {
stream.consume();
}
@Override
public int LA(int i) {
int c = stream.LA(i);
if (c <= 0) {
return c;
}
if (upper) {
return Character.toUpperCase(c);
}
return Character.toLowerCase(c);
}
@Override
public int mark() {
return stream.mark();
}
@Override
public void release(int marker) {
stream.release(marker);
}
@Override
public int index() {
return stream.index();
}
@Override
public void seek(int index) {
stream.seek(index);
}
@Override
public int size() {
return stream.size();
}
@Override
public String getSourceName() {
return stream.getSourceName();
}
}
| 2,218 | 23.932584 | 100 | java |
pmd | pmd-master/pmd-tsql/src/main/java/net/sourceforge/pmd/lang/tsql/cpd/TSqlTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.tsql.cpd;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.cpd.impl.AntlrTokenizer;
import net.sourceforge.pmd.lang.tsql.ast.TSqlLexer;
public class TSqlTokenizer extends AntlrTokenizer {
@Override
protected Lexer getLexerForSource(CharStream charStream) {
return new TSqlLexer(new CaseChangingCharStream(charStream, true));
}
}
| 528 | 25.45 | 79 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/CpdExecutor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import java.nio.file.Path;
import java.util.Arrays;
/**
* Executes CPD from command line. Deals with the differences, when CPD is run on Windows or on Linux.
*
* @author Andreas Dangel
*/
public class CpdExecutor {
private CpdExecutor() {
// this is a helper class only
}
/**
* Executes CPD found in tempDir with the given command line arguments.
* @param tempDir the directory, to which the binary distribution has been extracted
* @param arguments the arguments to execute CPD with
* @return collected result of the execution
* @throws Exception if the execution fails for any reason (executable not found, ...)
*/
public static ExecutionResult runCpd(Path tempDir, String... arguments) throws Exception {
return PMDExecutor.runCommand(tempDir, "cpd", Arrays.asList(arguments));
}
}
| 979 | 30.612903 | 102 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/PMDExecutor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.SystemUtils;
import net.sourceforge.pmd.internal.util.IOUtil;
/**
* Executes PMD from command line. Deals with the differences, when PMD is run on Windows or on Linux.
*
* @author Andreas Dangel
*/
public class PMDExecutor {
private static final String SOURCE_DIRECTORY_FLAG = "-d";
private static final String RULESET_FLAG = "-R";
private static final String FORMAT_FLAG = "-f";
private static final String FORMATTER = "text";
private static final String REPORTFILE_FLAG = "-r";
private static final String NO_PROGRESSBAR_FLAG = "--no-progress";
private PMDExecutor() {
// this is a helper class only
}
static ExecutionResult runCommand(Path tempDir, String cmd, List<String> arguments) throws Exception {
return runCommand(tempDir, cmd, arguments, null);
}
static ExecutionResult runCommand(Path tempDir, String cmd, List<String> arguments, Path reportFile) throws Exception {
final String pmdScript;
if (SystemUtils.IS_OS_WINDOWS) {
pmdScript = tempDir.resolve(AbstractBinaryDistributionTest.PMD_BIN_PREFIX + "/bin/pmd.bat").toAbsolutePath().toString();
} else {
pmdScript = tempDir.resolve(AbstractBinaryDistributionTest.PMD_BIN_PREFIX + "/bin/pmd").toAbsolutePath().toString();
}
ProcessBuilder pb = new ProcessBuilder(pmdScript);
pb.command().add(cmd);
pb.command().addAll(arguments);
pb.redirectErrorStream(false);
// Ensure no ANSI output so tests can properly look at it
pb.environment().put("PMD_JAVA_OPTS", "-Dpicocli.ansi=false");
final Process process = pb.start();
final ExecutionResult.Builder result = new ExecutionResult.Builder();
Thread outputReader = new Thread(new Runnable() {
@Override
public void run() {
String output;
try {
output = IOUtil.readToString(process.getInputStream(), StandardCharsets.UTF_8);
result.withOutput(output);
} catch (IOException e) {
result.withOutput("Exception occurred: " + e.toString());
}
}
});
outputReader.start();
Thread errorReader = new Thread(new Runnable() {
@Override
public void run() {
String error;
try {
error = IOUtil.readToString(process.getErrorStream(), StandardCharsets.UTF_8);
result.withErrorOutput(error);
} catch (IOException e) {
result.withErrorOutput("Exception occurred: " + e.toString());
}
}
});
errorReader.start();
int exitCode = process.waitFor();
outputReader.join(TimeUnit.MINUTES.toMillis(5));
errorReader.join(TimeUnit.MINUTES.toMillis(5));
String report = null;
if (reportFile != null) {
try (Reader reader = Files.newBufferedReader(reportFile, StandardCharsets.UTF_8)) {
report = IOUtil.readToString(reader);
}
}
return result.withExitCode(exitCode).withReport(report).build();
}
/**
* Executes the PMD found in tempDir against the given sourceDirectory path with the given ruleset.
*
* @param reportFile the file to write the report to
* @param tempDir the directory, to which the binary distribution has been extracted
* @param sourceDirectory the source directory, that PMD should analyze
* @param ruleset the ruleset, that PMD should execute
* @return collected result of the execution
* @throws Exception if the execution fails for any reason (executable not found, ...)
*/
public static ExecutionResult runPMDRules(Path reportFile, Path tempDir, String sourceDirectory, String ruleset) throws Exception {
return runPMDRules(reportFile, tempDir, sourceDirectory, ruleset, FORMATTER);
}
public static ExecutionResult runPMDRules(Path reportFile, Path tempDir, String sourceDirectory, String ruleset, String formatter) throws Exception {
return runPMD(reportFile, tempDir, SOURCE_DIRECTORY_FLAG, sourceDirectory, RULESET_FLAG, ruleset,
FORMAT_FLAG, formatter, NO_PROGRESSBAR_FLAG);
}
/**
* Executes PMD found in tempDir with the given command line arguments.
* @param reportFile The location where to store the result. If null, the report will be discarded.
* @param tempDir the directory, to which the binary distribution has been extracted
* @param arguments the arguments to execute PMD with
* @return collected result of the execution
* @throws Exception if the execution fails for any reason (executable not found, ...)
*/
public static ExecutionResult runPMD(Path reportFile, Path tempDir, String... arguments) throws Exception {
List<String> args = new ArrayList<>();
if (reportFile != null) {
args.add(REPORTFILE_FLAG);
args.add(reportFile.toString());
}
args.addAll(Arrays.asList(arguments));
return runCommand(tempDir, "check", args, reportFile);
}
}
| 5,666 | 39.769784 | 153 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/AnalysisCacheIT.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
class AnalysisCacheIT extends AbstractBinaryDistributionTest {
private final String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath();
@Test
void testPmdCachedResultMatches() throws Exception {
final Path cacheFile = createTemporaryReportFile();
ExecutionResult result = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-f", "text", "--cache", cacheFile.toAbsolutePath().toString(), "--no-progress");
// Ensure we have violations and a non-empty cache file
assertTrue(cacheFile.toFile().length() > 0, "cache file is empty after run");
result.assertExitCode(4).assertReport(containsString(srcDir + File.separator + "JumbledIncrementer.java:8:\tJumbledIncrementer:\t"));
// rerun from cache
ExecutionResult resultFromCache = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-f", "text", "--cache", cacheFile.toAbsolutePath().toString(), "--no-progress", "-v");
// expect identical
result.assertIdenticalResults(resultFromCache);
resultFromCache.assertErrorOutputContains("Incremental Analysis cache HIT");
}
@Test
void testPmdCachedResultsAreRelativized() throws Exception {
final Path cacheFile = createTemporaryReportFile();
ExecutionResult result = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-f", "text", "--cache", cacheFile.toAbsolutePath().toString(), "--no-progress");
// Ensure we have violations and a non-empty cache file
assertTrue(cacheFile.toFile().length() > 0, "cache file is empty after run");
result.assertExitCode(4)
.assertReport(containsString(srcDir + File.separator + "JumbledIncrementer.java:8:\tJumbledIncrementer:\t"));
// rerun from cache with relativized paths
ExecutionResult resultFromCache = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", Paths.get(".").toAbsolutePath().relativize(Paths.get(srcDir)).toString(), "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-f", "text", "--cache", cacheFile.toAbsolutePath().toString(), "--no-progress", "-v");
resultFromCache.assertErrorOutputContains("Incremental Analysis cache HIT");
// An error with the relative path should exist, but no with the absolute one
result.assertExitCode(4)
.assertReport(containsString("src/test/resources/sample-source/java/JumbledIncrementer.java:8:\tJumbledIncrementer:\t".replace('/', File.separatorChar)));
resultFromCache.assertNoErrorInReport(srcDir + File.separator + "JumbledIncrementer.java:8:\tJumbledIncrementer:\t");
}
}
| 3,340 | 51.203125 | 234 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/ExecutionResult.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.hamcrest.Matcher;
/**
* Collects the result of a command execution in order to verify it.
*
* @author Andreas Dangel
*/
public class ExecutionResult {
private final int exitCode;
private final String output;
private final String errorOutput;
private final String report;
ExecutionResult(int theExitCode, String theOutput, String theErrorOutput, String theReport) {
this.exitCode = theExitCode;
this.output = theOutput;
this.errorOutput = theErrorOutput;
this.report = theReport;
}
@Override
public String toString() {
return "ExecutionResult:\n"
+ " exit code: " + exitCode + "\n"
+ " output:\n" + output + "\n"
+ " errorOutput:\n" + errorOutput + "\n"
+ " report:\n" + report + "\n";
}
public ExecutionResult assertExitCode(int expectedExitCode) {
assertEquals(expectedExitCode, exitCode, "Command exited with wrong code.\nComplete result:\n\n" + this);
return this;
}
public ExecutionResult assertReport(Matcher<String> reportMatcher) {
assertThat("Report", report, reportMatcher);
return this;
}
public ExecutionResult assertStdErr(Matcher<String> matcher) {
assertThat("Standard error", errorOutput, matcher);
return this;
}
public ExecutionResult assertStdOut(Matcher<String> matcher) {
assertThat("Standard output", output, matcher);
return this;
}
public String getOutput() {
return output;
}
/**
* Asserts that the given error message is not in the error output.
*
* @param errorMessage the error message to search for
*/
public void assertNoError(String errorMessage) {
assertStdErr(not(containsString(errorMessage)));
}
/**
* Asserts that the given error message is not in the report.
* @param errorMessage the error message to search for
*/
public void assertNoErrorInReport(String errorMessage) {
assertReport(not(containsString(errorMessage)));
}
public void assertErrorOutputContains(String message) {
assertStdErr(containsString(message));
}
public void assertIdenticalResults(ExecutionResult other) {
// Notice we don't check for error output, as log messages may differ due to cache
assertEquals(exitCode, other.exitCode, "Exit codes differ");
assertEquals(output, other.output, "Outputs differ");
assertEquals(report, other.report, "Reports differ");
}
static class Builder {
private int exitCode;
private String output;
private String errorOutput;
private String report;
Builder withExitCode(int exitCode) {
this.exitCode = exitCode;
return this;
}
Builder withOutput(String output) {
this.output = output;
return this;
}
Builder withErrorOutput(String errorOutput) {
this.errorOutput = errorOutput;
return this;
}
Builder withReport(String report) {
this.report = report;
return this;
}
ExecutionResult build() {
return new ExecutionResult(exitCode, output, errorOutput, report);
}
}
}
| 3,664 | 28.556452 | 113 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/BinaryDistributionIT.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.matchesRegex;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDVersion;
class BinaryDistributionIT extends AbstractBinaryDistributionTest {
private static final List<String> SUPPORTED_LANGUAGES_CPD = listOf(
"apex", "coco", "cpp", "cs", "dart", "ecmascript",
"fortran", "gherkin", "go", "groovy", "html", "java", "jsp",
"julia",
"kotlin", "lua", "matlab", "modelica", "objectivec", "perl",
"php", "plsql", "python", "ruby", "scala", "swift", "tsql",
"typescript", "vf", "xml"
);
private static final List<String> SUPPORTED_LANGUAGES_PMD = listOf(
"apex-52", "apex-53", "apex-54", "apex-55",
"apex-56", "apex-57", "ecmascript-3", "ecmascript-5",
"ecmascript-6", "ecmascript-7", "ecmascript-8",
"ecmascript-9", "ecmascript-ES2015",
"ecmascript-ES2016", "ecmascript-ES2017",
"ecmascript-ES2018", "ecmascript-ES6", "html-4",
"html-5", "java-1.10", "java-1.3", "java-1.4", "java-1.5",
"java-1.6", "java-1.7", "java-1.8", "java-1.9", "java-10",
"java-11", "java-12", "java-13", "java-14", "java-15",
"java-16", "java-17", "java-18", "java-19",
"java-19-preview", "java-20", "java-20-preview",
"java-5", "java-6", "java-7",
"java-8", "java-9", "jsp-2", "jsp-3", "kotlin-1.6",
"kotlin-1.7", "kotlin-1.8", "modelica-3.4", "modelica-3.5",
"plsql-11g", "plsql-12.1", "plsql-12.2",
"plsql-12c_Release_1", "plsql-12c_Release_2",
"plsql-18c", "plsql-19c", "plsql-21c", "pom-4.0.0",
"scala-2.10", "scala-2.11", "scala-2.12", "scala-2.13",
"swift-4.2", "swift-5.0", "swift-5.1", "swift-5.2",
"swift-5.3", "swift-5.4", "swift-5.5", "swift-5.6",
"swift-5.7", "vf-52", "vf-53", "vf-54", "vf-55", "vf-56",
"vf-57", "vm-2.0", "vm-2.1", "vm-2.2", "vm-2.3", "wsdl-1.1",
"wsdl-2.0", "xml-1.0", "xml-1.1", "xsl-1.0", "xsl-2.0",
"xsl-3.0"
);
private final String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath();
private static Pattern toListPattern(List<String> items) {
String pattern = items.stream().map(Pattern::quote)
.collect(Collectors.joining(",", ".*Validvalues:", ".*"));
return Pattern.compile(pattern, Pattern.DOTALL);
}
@Test
void testFileExistence() {
assertTrue(getBinaryDistribution().exists());
}
private Set<String> getExpectedFileNames() {
Set<String> result = new HashSet<>();
String basedir = "pmd-bin-" + PMDVersion.VERSION + "/";
result.add(basedir);
result.add(basedir + "LICENSE");
result.add(basedir + "bin/pmd");
result.add(basedir + "bin/pmd.bat");
result.add(basedir + "conf/simplelogger.properties");
result.add(basedir + "shell/pmd-completion.sh");
result.add(basedir + "lib/pmd-core-" + PMDVersion.VERSION + ".jar");
result.add(basedir + "lib/pmd-java-" + PMDVersion.VERSION + ".jar");
result.add(basedir + "sbom/pmd-" + PMDVersion.VERSION + "-cyclonedx.xml");
result.add(basedir + "sbom/pmd-" + PMDVersion.VERSION + "-cyclonedx.json");
return result;
}
@Test
void testZipFileContent() throws IOException {
Set<String> expectedFileNames = getExpectedFileNames();
ZipFile zip = new ZipFile(getBinaryDistribution());
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
expectedFileNames.remove(entry.getName());
}
zip.close();
if (!expectedFileNames.isEmpty()) {
fail("Missing files in archive: " + expectedFileNames);
}
}
@Test
void testPmdJavaQuickstart() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "rulesets/java/quickstart.xml");
result.assertExitCode(4)
.assertStdOut(containsString(""));
}
@Test
void testPmdXmlFormat() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml", "xml");
result.assertExitCode(4).assertReport(containsString("JumbledIncrementer.java\">"));
result.assertExitCode(4).assertReport(containsString("<violation beginline=\"8\" endline=\"10\" begincolumn=\"13\" endcolumn=\"14\" rule=\"JumbledIncrementer\""));
}
@Test
void testPmdSample() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExitCode(4).assertReport(containsString("JumbledIncrementer.java:8:"));
}
@Test
void testPmdSampleWithZippedSources() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir + "/sample-source-java.zip",
"src/test/resources/rulesets/sample-ruleset.xml");
result.assertExitCode(4).assertReport(containsString("JumbledIncrementer.java:8:"));
}
@Test
void testPmdSampleWithJarredSources() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir + "/sample-source-java.jar",
"src/test/resources/rulesets/sample-ruleset.xml");
result.assertExitCode(4).assertReport(containsString("JumbledIncrementer.java:8:"));
}
@Test
void testPmdHelp() throws Exception {
ExecutionResult result = PMDExecutor.runPMD(null, tempDir, "-h");
result.assertExitCode(0);
String output = result.getOutput().replaceAll("\\s+|\r|\n", "");
assertThat(output, matchesRegex(toListPattern(SUPPORTED_LANGUAGES_PMD)));
}
@Test
void testPmdNoArgs() throws Exception {
ExecutionResult result = PMDExecutor.runPMD(null, tempDir); // without any argument, display usage help and error
result.assertExitCode(2).assertStdErr(containsString("Usage: pmd check "));
}
@Test
void logging() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath();
ExecutionResult result;
result = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExitCode(4);
result.assertErrorOutputContains("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at INFO");
// now with debug
result = PMDExecutor.runPMD(createTemporaryReportFile(), tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml", "--debug");
result.assertExitCode(4);
result.assertErrorOutputContains("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at TRACE");
}
@Test
void runPMDWithError() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/unparsable/").getAbsolutePath();
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExitCode(0).assertStdErr(containsString("Run in verbose mode to see a stack-trace."));
}
@Test
void runCPD() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source-cpd/").getAbsolutePath();
ExecutionResult result;
result = CpdExecutor.runCpd(tempDir); // without any argument, display usage help and error
result.assertExitCode(2).assertStdErr(containsString("Usage: pmd cpd "));
result = CpdExecutor.runCpd(tempDir, "-h");
result.assertExitCode(0);
String output = result.getOutput().replaceAll("\\s+|\r|\n", "");
assertThat(output, matchesRegex(toListPattern(SUPPORTED_LANGUAGES_CPD)));
result = CpdExecutor.runCpd(tempDir, "--minimum-tokens", "10", "--format", "text", "--dir", srcDir);
result.assertExitCode(4)
.assertStdOut(containsString("Found a 10 line (55 tokens) duplication in the following files:"));
result.assertExitCode(4)
.assertStdOut(containsString("Class1.java"));
result.assertExitCode(4)
.assertStdOut(containsString("Class2.java"));
result = CpdExecutor.runCpd(tempDir, "--minimum-tokens", "10", "--format", "xml", "--dir", srcDir);
result.assertExitCode(4)
.assertStdOut(containsString("<duplication lines=\"10\" tokens=\"55\">"));
result.assertExitCode(4)
.assertStdOut(containsString("Class1.java\"/>"));
result.assertExitCode(4)
.assertStdOut(containsString("Class2.java\"/>"));
result = CpdExecutor.runCpd(tempDir, "--minimum-tokens", "1000", "--format", "text", "--dir", srcDir);
result.assertExitCode(0);
}
@Test
void runAstDump() throws Exception {
File jumbledIncrementerSrc = new File(srcDir, "JumbledIncrementer.java");
List<String> args = listOf("--format", "xml", "--language", "java", "--file", jumbledIncrementerSrc.toString());
ExecutionResult result = PMDExecutor.runCommand(tempDir, "ast-dump", args);
result.assertExitCode(0);
}
}
| 10,271 | 42.897436 | 171 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/SourceDistributionIT.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDVersion;
class SourceDistributionIT {
private static final String BASE_PATH = "pmd-src-" + PMDVersion.VERSION;
private File getSourceDistribution() {
return new File(".", "target/pmd-dist-" + PMDVersion.VERSION + "-src.zip");
}
@Test
void testFileExistence() {
assertTrue(getSourceDistribution().exists());
}
@Test
void verifyExclusions() throws Exception {
Set<String> exclusions = new HashSet<>();
exclusions.add(BASE_PATH + "/.ci/files/id_rsa");
exclusions.add(BASE_PATH + "/.ci/files/private-env");
exclusions.add(BASE_PATH + "/.ci/files/public-env");
exclusions.add(BASE_PATH + "/.ci/files/release-signing-key-D0BF1D737C9A1C22.gpg.gpg");
List<String> files = ZipFileExtractor.readZipFile(getSourceDistribution().toPath());
for (String file : files) {
assertFalse(exclusions.contains(file), "File " + file + " must not be included");
}
}
}
| 1,378 | 29.644444 | 94 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/ZipFileExtractor.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import net.sourceforge.pmd.internal.util.IOUtil;
/**
* Extracts a zip file with preserving the unix file permissions.
*
* @author Andreas Dangel
*/
public class ZipFileExtractor {
// unix file permission for executable flag by owner
private static final int OWNER_EXECUTABLE = 0x40;
private ZipFileExtractor() {
// Helper class
}
/**
* Extracts the given zip file into the tempDir.
* @param zipPath the zip file to extract
* @param tempDir the target directory
* @throws Exception if any error happens during extraction
*/
public static void extractZipFile(Path zipPath, Path tempDir) throws Exception {
try (ZipFile zip = new ZipFile(zipPath.toFile())) {
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
File file = tempDir.resolve(entry.getName()).toFile();
if (entry.isDirectory()) {
assertTrue(file.mkdirs());
} else {
try (InputStream data = zip.getInputStream(entry);
OutputStream fileOut = new FileOutputStream(file);) {
IOUtil.copy(data, fileOut);
}
if ((entry.getUnixMode() & OWNER_EXECUTABLE) == OWNER_EXECUTABLE) {
file.setExecutable(true);
}
}
}
}
}
/**
* Compiles a list of all the files/directories contained in the given zip file.
* @param zipPath the zip file to look into
* @return list of all entries
* @throws Exception if any error happens during read of the zip file
*/
public static List<String> readZipFile(Path zipPath) throws Exception {
List<String> result = new ArrayList<>();
try (ZipFile zip = new ZipFile(zipPath.toFile())) {
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
result.add(entry.getName());
}
}
return result;
}
}
| 2,777 | 33.296296 | 87 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/AbstractBinaryDistributionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDVersion;
abstract class AbstractBinaryDistributionTest {
public static final String PMD_BIN_PREFIX = "pmd-bin-" + PMDVersion.VERSION;
protected static File getBinaryDistribution() {
return new File(".", "target/pmd-dist-" + PMDVersion.VERSION + "-bin.zip");
}
@TempDir
static Path folder;
/**
* The temporary directory, to which the binary distribution will be extracted.
* It will be deleted again after the test.
*/
protected static Path tempDir;
protected Path createTemporaryReportFile() throws IOException {
return Files.createTempFile(folder, null, null);
}
@BeforeAll
static void setupTempDirectory() throws Exception {
tempDir = Files.createTempDirectory(folder, null);
if (getBinaryDistribution().exists()) {
ZipFileExtractor.extractZipFile(getBinaryDistribution().toPath(), tempDir);
}
}
}
| 1,259 | 27 | 87 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/AllRulesIT.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.hamcrest.Matchers.containsString;
import java.io.File;
import java.util.Arrays;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class AllRulesIT extends AbstractBinaryDistributionTest {
static Iterable<String> languagesToTest() {
// note: scala and wsdl have no rules
return Arrays.asList("java", "apex", "html", "javascript", "jsp", "modelica",
"plsql", "pom", "visualforce", "velocitytemplate", "xml", "xsl");
}
@ParameterizedTest
@MethodSource("languagesToTest")
void runRuleTests(String language) throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/" + language + "/").getAbsolutePath();
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir,
"src/test/resources/rulesets/all-" + language + ".xml");
assertDefaultExecutionResult(result);
}
private static void assertDefaultExecutionResult(ExecutionResult result) {
result.assertExitCode(4)
.assertStdOut(containsString(""));
result.assertNoError("Exception applying rule");
result.assertNoError("Ruleset not found");
result.assertNoError("Use of deprecated attribute");
result.assertNoError("instead of the deprecated"); // rule deprecations
result.assertNoErrorInReport("Error while processing");
result.assertNoErrorInReport("Error while parsing");
// See bug #2092: [apex] ApexLexer logs visible when Apex is the selected language upon starting the designer
result.assertNoError("Deduped array ApexLexer");
}
}
| 1,836 | 36.489796 | 117 | java |
pmd | pmd-master/pmd-dist/src/test/java/net/sourceforge/pmd/it/AntIT.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.it;
import static org.hamcrest.Matchers.containsString;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import net.sourceforge.pmd.internal.util.IOUtil;
/**
* This test calls ant in a fake terminal to make sure we have a {@link java.io.Console} connected.
* This however only works under linux.
* <p>
* See <a href="# https://stackoverflow.com/questions/1401002/how-to-trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe/20401674#20401674">How to trick an application into thinking its stdout is a terminal, not a pipe</a>.
*/
class AntIT extends AbstractBinaryDistributionTest {
@Test
@EnabledOnOs(OS.LINUX)
void runAnt() throws IOException, InterruptedException {
String antBasepath = new File("target/ant").getAbsolutePath();
String pmdHome = tempDir.resolve(PMD_BIN_PREFIX).toAbsolutePath().toString();
File antTestProjectFolder = prepareAntTestProjectFolder();
ExecutionResult result = runAnt(antBasepath, pmdHome, antTestProjectFolder);
result.assertExitCode(0)
.assertStdOut(containsString("BUILD SUCCESSFUL"));
// the no package rule
result.assertExitCode(0)
.assertStdOut(containsString("NoPackage"));
}
private File prepareAntTestProjectFolder() throws IOException {
final Path sourceProjectFolder = new File("src/test/resources/ant-it").toPath();
final Path projectFolder = Files.createTempDirectory(folder, null);
Files.walkFileTree(sourceProjectFolder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
assert !dir.isAbsolute();
Path target = projectFolder.resolve(sourceProjectFolder.relativize(dir));
if (!target.toFile().exists()) {
target.toFile().mkdir();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
assert !file.isAbsolute();
Path target = projectFolder.resolve(sourceProjectFolder.relativize(file));
Files.copy(file, target);
return FileVisitResult.CONTINUE;
}
});
return projectFolder.toFile();
}
private ExecutionResult runAnt(String antLibPath, String pmdHomePath, File antTestProjectFolder)
throws IOException, InterruptedException {
String cmd = System.getenv("JAVA_HOME") + "/bin/java" + " -cp \"" + antLibPath + "/*\""
+ " -jar " + antLibPath + "/ant-launcher.jar -Dpmd.home=" + pmdHomePath;
// https://stackoverflow.com/questions/1401002/how-to-trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe/20401674#20401674
ProcessBuilder pb = new ProcessBuilder("script", "-qfec", cmd, "/dev/null");
pb.directory(antTestProjectFolder);
pb.redirectErrorStream(true);
final ExecutionResult.Builder result = new ExecutionResult.Builder();
final Process process = pb.start();
Thread outputReader = new Thread(new Runnable() {
@Override
public void run() {
try (InputStream in = process.getInputStream()) {
String output = IOUtil.readToString(process.getInputStream(), StandardCharsets.UTF_8);
result.withOutput(output);
} catch (IOException e) {
result.withOutput("Exception occurred: " + e.toString());
}
}
});
outputReader.start();
int exitCode = process.waitFor();
outputReader.join(TimeUnit.SECONDS.toMillis(5));
result.withExitCode(exitCode);
return result.build();
}
}
| 4,451 | 40.607477 | 242 | java |
pmd | pmd-master/pmd-dist/src/test/resources/ant-it/src/Sample.java | public class Sample {}
| 23 | 11 | 22 | java |
pmd | pmd-master/pmd-dist/src/test/resources/sample-source-cpd/Class1.java | /**
* Example for a test CPD run to detect duplicates.
*/
public class Class1 {
public void duplicatedMethod() {
int x = 1;
int y = 2;
int z = x * y;
int a = x * x + y * y;
System.out.println("x=" + x + ",y=" + y + ",z=" + z + ",a=" + a);
}
}
| 294 | 20.071429 | 73 | java |
pmd | pmd-master/pmd-dist/src/test/resources/sample-source-cpd/Class2.java | /**
* Example for a test CPD run to detect duplicates.
*/
public class Class2 {
public void duplicatedMethod() {
int x = 1;
int y = 2;
int z = x * y;
int a = x * x + y * y;
System.out.println("x=" + x + ",y=" + y + ",z=" + z + ",a=" + a);
}
}
| 294 | 20.071429 | 73 | java |
pmd | pmd-master/pmd-dist/src/test/resources/sample-source/unparsable/cannot_be_parsed.java |
{} // not a valid file
| 25 | 5.5 | 22 | java |
pmd | pmd-master/pmd-dist/src/test/resources/sample-source/java/JumbledIncrementer.java | /**
* Sample file which triggers the JumbledIncrementerRule on line 8.
* Used in the integration tests.
*/
public class JumbledIncrementer {
public void foo() {
for (int i = 0; i < 10; i++) { // only references 'i'
for (int k = 0; k < 20; i++) { // references both 'i' and 'k'
System.out.println("Hello");
}
}
}
}
| 395 | 27.285714 | 78 | java |
pmd | pmd-master/pmd-test-schema/src/test/java/net/sourceforge/pmd/test/schema/TestSchemaParserTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
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.assertThrows;
import java.io.IOException;
import java.io.StringReader;
import org.junit.jupiter.api.Test;
import org.xml.sax.InputSource;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.PlainTextLanguage;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import com.github.stefanbirkner.systemlambda.SystemLambda;
/**
* @author Clément Fournier
*/
class TestSchemaParserTest {
@Test
void testSchemaSimple() throws IOException {
String file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<test-data\n"
+ " xmlns=\"http://pmd.sourceforge.net/rule-tests\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/rule-tests net/sourceforge/pmd/test/schema/rule-tests_1_0_0.xsd\">\n"
+ " <test-code>\n"
+ " <description>equality operators with Double.NaN</description>\n"
+ " <expected-problems>4</expected-problems>\n"
+ " <code><![CDATA[\n"
+ " public class Foo {\n"
+ " }\n"
+ " ]]></code>\n"
+ " </test-code>\n"
+ " <test-code>\n"
+ " <description>equality operators with Float.NaN</description>\n"
+ " <expected-problems>4</expected-problems>\n"
+ " <code><![CDATA[\n"
+ " public class Foo {\n"
+ " }\n"
+ " ]]></code>\n"
+ " </test-code>\n"
+ "</test-data>\n";
RuleTestCollection parsed = parseFile(file);
assertEquals(2, parsed.getTests().size());
}
@Test
void testSchemaDeprecatedAttr() throws Exception {
String file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<test-data\n"
+ " xmlns=\"http://pmd.sourceforge.net/rule-tests\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/rule-tests net/sourceforge/pmd/test/schema/rule-tests_1_0_0.xsd\">\n"
+ " <test-code regressionTest='false'>\n"
+ " <description>equality operators with Double.NaN</description>\n"
+ " <expected-problems>4</expected-problems>\n"
+ " <code><![CDATA[\n"
+ " public class Foo {\n"
+ " }\n"
+ " ]]></code>\n"
+ " </test-code>\n"
+ "</test-data>\n";
String log = SystemLambda.tapSystemErr(() -> {
RuleTestCollection parsed = parseFile(file);
assertEquals(1, parsed.getTests().size());
});
assertThat(log, containsString(" 6| <test-code regressionTest='false'>\n"
+ " ^^^^^^^^^^^^^^ Attribute 'regressionTest' is deprecated, use 'disabled' with inverted value\n"));
}
@Test
void testUnknownProperty() throws Exception {
String file = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<test-data\n"
+ " xmlns=\"http://pmd.sourceforge.net/rule-tests\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://pmd.sourceforge.net/rule-tests net/sourceforge/pmd/test/schema/rule-tests_1_0_0.xsd\">\n"
+ " <test-code>\n"
+ " <description>equality operators with Double.NaN</description>\n"
+ " <rule-property name='invalid_property'>foo</rule-property>\n"
+ " <expected-problems>0</expected-problems>\n"
+ " <code><![CDATA[\n"
+ " public class Foo {\n"
+ " }\n"
+ " ]]></code>\n"
+ " </test-code>\n"
+ "</test-data>\n";
String log = SystemLambda.tapSystemErr(() -> {
assertThrows(IllegalStateException.class, () -> parseFile(file));
});
assertThat(log, containsString(" 8| <rule-property name='invalid_property'>foo</rule-property>\n"
+ " ^^^^ Unknown property, known property names are violationSuppressRegex, violationSuppressXPath\n"));
}
private RuleTestCollection parseFile(String file) throws IOException {
MockRule mockRule = new MockRule();
mockRule.setLanguage(PlainTextLanguage.getInstance());
InputSource is = new InputSource();
is.setSystemId("a/file.xml");
is.setCharacterStream(new StringReader(file));
return new TestSchemaParser().parse(mockRule, is);
}
public static final class MockRule extends AbstractRule {
@Override
public void apply(Node target, RuleContext ctx) {
// do nothing
}
}
}
| 5,884 | 43.923664 | 176 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/package-info.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
/**
* Contains a parser for the XML test format.
*/
package net.sourceforge.pmd.test.schema;
| 184 | 17.5 | 79 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/BaseTestParserImpl.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertySource;
import net.sourceforge.pmd.test.schema.TestSchemaParser.PmdXmlReporter;
import com.github.oowekyala.ooxml.DomUtils;
import com.github.oowekyala.ooxml.messages.PositionedXmlDoc;
import com.github.oowekyala.ooxml.messages.XmlPosition;
import com.github.oowekyala.ooxml.messages.XmlPositioner;
/**
* @author Clément Fournier
*/
class BaseTestParserImpl {
static class ParserV1 extends BaseTestParserImpl {
}
public RuleTestCollection parseDocument(Rule rule, PositionedXmlDoc positionedXmlDoc, PmdXmlReporter err) {
Document doc = positionedXmlDoc.getDocument();
Element root = doc.getDocumentElement();
Map<String, Element> codeFragments = parseCodeFragments(err, root);
Set<String> usedFragments = new HashSet<>();
List<Element> testCodes = DomUtils.childrenNamed(root, "test-code");
RuleTestCollection result = new RuleTestCollection();
for (int i = 0; i < testCodes.size(); i++) {
RuleTestDescriptor descriptor = new RuleTestDescriptor(i, rule.deepCopy());
try (PmdXmlReporter errScope = err.newScope()) {
parseSingleTest(testCodes.get(i), descriptor, codeFragments, usedFragments, positionedXmlDoc.getPositioner(), errScope);
if (!errScope.hasError()) {
result.addTest(descriptor);
}
}
}
codeFragments.keySet().removeAll(usedFragments);
codeFragments.forEach((id, node) -> err.at(node).warn("Unused code fragment"));
return result;
}
private Map<String, Element> parseCodeFragments(PmdXmlReporter err, Element root) {
Map<String, Element> codeFragments = new HashMap<>();
for (Element node : DomUtils.childrenNamed(root, "code-fragment")) {
Attr id = getRequiredAttribute("id", node, err);
if (id == null) {
continue;
}
Element prev = codeFragments.put(id.getValue(), node);
if (prev != null) {
err.at(prev).error("Fragment with duplicate id ''{0}'' is ignored", id.getValue());
}
}
return codeFragments;
}
private void parseSingleTest(Element testCode,
RuleTestDescriptor descriptor,
Map<String, Element> fragments,
Set<String> usedFragments,
XmlPositioner xmlPositioner,
PmdXmlReporter err) {
{
String description = getSingleChildText(testCode, "description", true, err);
if (description == null) {
return;
}
descriptor.setDescription(description);
}
parseBoolAttribute(testCode, "reinitializeRule", true, err, "Attribute 'reinitializeRule' is deprecated and ignored, assumed true");
parseBoolAttribute(testCode, "useAuxClasspath", true, err, "Attribute 'useAuxClasspath' is deprecated and ignored, assumed true");
boolean disabled = parseBoolAttribute(testCode, "disabled", false, err, null)
| !parseBoolAttribute(testCode, "regressionTest", true, err, "Attribute ''regressionTest'' is deprecated, use ''disabled'' with inverted value");
descriptor.setDisabled(disabled);
boolean focused = parseBoolAttribute(testCode, "focused", false, err,
"Attribute focused is used, do not forget to remove it when checking in sources");
descriptor.setFocused(focused);
Properties properties = parseRuleProperties(testCode, descriptor.getRule(), err);
descriptor.getProperties().putAll(properties);
parseExpectedProblems(testCode, descriptor, err);
String code = getTestCode(testCode, fragments, usedFragments, err);
if (code == null) {
return;
}
descriptor.setCode(code);
LanguageVersion lversion = parseLanguageVersion(testCode, err);
if (lversion != null) {
descriptor.setLanguageVersion(lversion);
}
XmlPosition startPosition = xmlPositioner.startPositionOf(testCode);
descriptor.setLineNumber(startPosition.getLine());
}
private void parseExpectedProblems(Element testCode, RuleTestDescriptor descriptor, PmdXmlReporter err) {
Node expectedProblemsNode = getSingleChild(testCode, "expected-problems", true, err);
if (expectedProblemsNode == null) {
return;
}
int expectedProblems = Integer.parseInt(parseTextNode(expectedProblemsNode));
List<String> expectedMessages = Collections.emptyList();
{
Element messagesNode = getSingleChild(testCode, "expected-messages", false, err);
if (messagesNode != null) {
expectedMessages = new ArrayList<>();
List<Element> messageNodes = DomUtils.childrenNamed(messagesNode, "message");
if (messageNodes.size() != expectedProblems) {
err.at(expectedProblemsNode).error("Number of ''expected-messages'' ({0}) does not match", messageNodes.size());
return;
}
for (Node message : messageNodes) {
expectedMessages.add(parseTextNode(message));
}
}
}
List<Integer> expectedLineNumbers = Collections.emptyList();
{
Element lineNumbers = getSingleChild(testCode, "expected-linenumbers", false, err);
if (lineNumbers != null) {
expectedLineNumbers = new ArrayList<>();
String[] linenos = parseTextNode(lineNumbers).split(",");
if (linenos.length != expectedProblems) {
err.at(expectedProblemsNode).error("Number of ''expected-linenumbers'' ({0}) does not match", linenos.length);
return;
}
for (String num : linenos) {
expectedLineNumbers.add(Integer.valueOf(num.trim()));
}
}
}
descriptor.recordExpectedViolations(
expectedProblems,
expectedLineNumbers,
expectedMessages
);
}
private String getTestCode(Element testCode, Map<String, Element> fragments, Set<String> usedFragments, PmdXmlReporter err) {
String code = getSingleChildText(testCode, "code", false, err);
if (code == null) {
// Should have a coderef
List<Element> coderefs = DomUtils.childrenNamed(testCode, "code-ref");
if (coderefs.isEmpty()) {
throw new RuntimeException(
"Required tag is missing from the test-xml. Supply either a code or a code-ref tag");
}
Element coderef = coderefs.get(0);
Attr id = getRequiredAttribute("id", coderef, err);
if (id == null) {
return null;
}
Element fragment = fragments.get(id.getValue());
if (fragment == null) {
err.at(id).error("Unknown id, known IDs are {0}", fragments.keySet());
return null;
}
usedFragments.add(id.getValue());
code = parseTextNodeNoTrim(fragment);
code = code.trim(); // todo replace with trimIndent in PMD 7
}
return code;
}
private LanguageVersion parseLanguageVersion(Element testCode, PmdXmlReporter err) {
Node sourceTypeNode = getSingleChild(testCode, "source-type", false, err);
if (sourceTypeNode == null) {
return null;
}
String languageVersionString = parseTextNode(sourceTypeNode);
LanguageVersion languageVersion = parseSourceType(languageVersionString);
if (languageVersion != null) {
return languageVersion;
}
err.at(sourceTypeNode).error("Unknown language version ''{0}''", languageVersionString);
return null;
}
/** FIXME this is stupid, the language version may be of a different language than the Rule... */
private static LanguageVersion parseSourceType(String terseNameAndVersion) {
final String version;
final String terseName;
if (terseNameAndVersion.contains(" ")) {
version = StringUtils.trimToNull(terseNameAndVersion.substring(terseNameAndVersion.lastIndexOf(' ') + 1));
terseName = terseNameAndVersion.substring(0, terseNameAndVersion.lastIndexOf(' '));
} else {
version = null;
terseName = terseNameAndVersion;
}
Language language = LanguageRegistry.findLanguageByTerseName(terseName);
if (language != null) {
if (version == null) {
return language.getDefaultVersion();
} else {
return language.getVersion(version);
}
}
return null;
}
private Properties parseRuleProperties(Element testCode, PropertySource knownProps, PmdXmlReporter err) {
Properties properties = new Properties();
for (Element ruleProperty : DomUtils.childrenNamed(testCode, "rule-property")) {
Node nameAttr = getRequiredAttribute("name", ruleProperty, err);
if (nameAttr == null) {
continue;
}
String propertyName = nameAttr.getNodeValue();
if (knownProps.getPropertyDescriptor(propertyName) == null) {
String knownNames = knownProps.getPropertyDescriptors().stream().map(PropertyDescriptor::name)
.collect(Collectors.joining(", "));
err.at(nameAttr).error("Unknown property, known property names are {0}", knownNames);
continue;
}
properties.setProperty(propertyName, parseTextNode(ruleProperty));
}
return properties;
}
private Attr getRequiredAttribute(String name, Element ruleProperty, PmdXmlReporter err) {
Attr nameAttr = (Attr) ruleProperty.getAttributes().getNamedItem(name);
if (nameAttr == null) {
err.at(ruleProperty).error("Missing ''{0}'' attribute", name);
return null;
}
return nameAttr;
}
private boolean parseBoolAttribute(Element testCode, String attrName, boolean defaultValue, PmdXmlReporter err, String deprecationMessage) {
Attr attrNode = testCode.getAttributeNode(attrName);
if (attrNode != null) {
if (deprecationMessage != null) {
err.at(attrNode).warn(deprecationMessage);
}
return Boolean.parseBoolean(attrNode.getNodeValue());
}
return defaultValue;
}
private String getSingleChildText(Element parentElm, String nodeName, boolean required, PmdXmlReporter err) {
Node node = getSingleChild(parentElm, nodeName, required, err);
if (node == null) {
return null;
}
return parseTextNode(node);
}
private Element getSingleChild(Element parentElm, String nodeName, boolean required, PmdXmlReporter err) {
List<Element> nodes = DomUtils.childrenNamed(parentElm, nodeName);
if (nodes.isEmpty()) {
if (required) {
err.at(parentElm).error("Required child ''{0}'' is missing", nodeName);
}
return null;
} else if (nodes.size() > 1) {
err.at(nodes.get(1)).error("Duplicate tag ''{0}'' is ignored", nodeName);
}
return nodes.get(0);
}
private static String parseTextNode(Node exampleNode) {
return parseTextNodeNoTrim(exampleNode).trim();
}
private static String parseTextNodeNoTrim(Node exampleNode) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < exampleNode.getChildNodes().getLength(); i++) {
Node node = exampleNode.getChildNodes().item(i);
if (node.getNodeType() == Node.CDATA_SECTION_NODE || node.getNodeType() == Node.TEXT_NODE) {
buffer.append(node.getNodeValue());
}
}
return buffer.toString();
}
}
| 13,070 | 38.972477 | 171 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/TestSchemaParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.function.Consumer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.annotation.Experimental;
import com.github.oowekyala.ooxml.messages.NiceXmlMessageSpec;
import com.github.oowekyala.ooxml.messages.OoxmlFacade;
import com.github.oowekyala.ooxml.messages.PositionedXmlDoc;
import com.github.oowekyala.ooxml.messages.PrintStreamMessageHandler;
import com.github.oowekyala.ooxml.messages.XmlException;
import com.github.oowekyala.ooxml.messages.XmlMessageReporter;
import com.github.oowekyala.ooxml.messages.XmlMessageReporterBase;
import com.github.oowekyala.ooxml.messages.XmlPosition;
import com.github.oowekyala.ooxml.messages.XmlPositioner;
import com.github.oowekyala.ooxml.messages.XmlSeverity;
/**
* Entry point to parse a test file.
*
* @author Clément Fournier
*/
@Experimental
public class TestSchemaParser {
private final TestSchemaVersion version;
TestSchemaParser(TestSchemaVersion version) {
this.version = version;
}
public TestSchemaParser() {
this(TestSchemaVersion.V1);
}
/**
* Entry point to parse a test file.
*
* @param rule Rule which owns the tests
* @param inputSource Where to access the test file to parse
*
* @return A test collection, possibly incomplete
*
* @throws IOException If parsing throws this
* @throws XmlException If parsing throws this
*/
public RuleTestCollection parse(Rule rule, InputSource inputSource) throws IOException, XmlException {
// note: need to explicitly specify the writer here, so that in unit tests
// System.err can be swapped out and in
OoxmlFacade ooxml = new OoxmlFacade().withPrinter(new PrintStreamMessageHandler(System.err));
PositionedXmlDoc doc = ooxml.parse(newDocumentBuilder(), inputSource);
try (PmdXmlReporterImpl err = new PmdXmlReporterImpl(ooxml, doc.getPositioner())) {
RuleTestCollection collection = version.getParserImpl().parseDocument(rule, doc, err);
if (err.hasError()) {
// todo maybe add a way not to throw here
throw new IllegalStateException("Errors were encountered while parsing XML tests");
}
return collection;
}
}
interface PmdXmlReporter extends XmlMessageReporter<Reporter> {
boolean hasError();
PmdXmlReporter newScope();
}
private static class PmdXmlReporterImpl
extends XmlMessageReporterBase<Reporter>
implements PmdXmlReporter {
private boolean hasError;
protected PmdXmlReporterImpl(OoxmlFacade ooxml,
XmlPositioner positioner) {
super(ooxml, positioner);
}
@Override
protected Reporter create2ndStage(XmlPosition position, XmlPositioner positioner) {
return new Reporter(position, positioner, ooxml, this::handleEx);
}
@Override
protected void handleEx(XmlException e) {
super.handleEx(e);
hasError |= e.getSeverity() == XmlSeverity.ERROR;
}
@Override
public PmdXmlReporter newScope() {
return new PmdXmlReporterImpl(ooxml, positioner) {
@Override
protected void handleEx(XmlException e) {
super.handleEx(e);
PmdXmlReporterImpl.this.hasError |= this.hasError();
}
};
}
@Override
public boolean hasError() {
return hasError;
}
}
private DocumentBuilder newDocumentBuilder() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// don't use the schema as it adds deprecated attributes implicitly...
// dbf.setSchema(version.getSchema());
dbf.setNamespaceAware(true);
return dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
static final class Reporter {
private final XmlPosition position;
private final XmlPositioner positioner;
private final OoxmlFacade ooxml;
private final Consumer<XmlException> handler;
private Reporter(XmlPosition position, XmlPositioner positioner, OoxmlFacade ooxml, Consumer<XmlException> handler) {
this.position = position;
this.positioner = positioner;
this.ooxml = ooxml;
this.handler = handler;
}
public void warn(String messageFormat, Object... args) {
reportImpl(XmlSeverity.WARNING, MessageFormat.format(messageFormat, args));
}
public void error(String messageFormat, Object... args) {
reportImpl(XmlSeverity.ERROR, MessageFormat.format(messageFormat, args));
}
private void reportImpl(XmlSeverity severity, String formattedMessage) {
NiceXmlMessageSpec spec =
new NiceXmlMessageSpec(position, formattedMessage)
.withSeverity(severity);
String fullMessage = ooxml.getFormatter().formatSpec(ooxml, spec, positioner);
XmlException ex = new XmlException(spec, fullMessage);
handler.accept(ex);
}
}
}
| 5,710 | 32.397661 | 125 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/TestSchemaVersion.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
import java.net.URL;
import java.util.Objects;
import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
/**
* Internal for now, there's only one version.
*
* @author Clément Fournier
*/
enum TestSchemaVersion {
V1("rule-tests_1_0_0.xsd", new BaseTestParserImpl.ParserV1());
private final Schema schema;
private String schemaLoc;
private BaseTestParserImpl parser;
TestSchemaVersion(String schemaLoc, BaseTestParserImpl parser) {
this.schemaLoc = schemaLoc;
this.parser = parser;
this.schema = parseSchema();
}
BaseTestParserImpl getParserImpl() {
return parser;
}
public Schema getSchema() {
return schema;
}
private Schema parseSchema() {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
return schemaFactory.newSchema(locateSchema());
} catch (SAXException e) {
throw new RuntimeException("Cannot parse schema " + this, e);
}
}
private URL locateSchema() {
URL resource = TestSchemaVersion.class.getResource(schemaLoc);
return Objects.requireNonNull(resource, "Cannot find schema location " + schemaLoc);
}
}
| 1,458 | 25.053571 | 100 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/RuleTestCollection.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Collection of individual rule tests. Each test contains a copy of the
* rule.
*
* @author Clément Fournier
*/
public class RuleTestCollection {
private final List<RuleTestDescriptor> tests = new ArrayList<>();
private String absoluteUriToTestXmlFile;
public void addTest(RuleTestDescriptor descriptor) {
tests.add(Objects.requireNonNull(descriptor));
}
public List<RuleTestDescriptor> getTests() {
return Collections.unmodifiableList(tests);
}
/**
* Returns the last test of the collection which is focused.
*/
public RuleTestDescriptor getFocusedTestOrNull() {
RuleTestDescriptor focused = null;
for (RuleTestDescriptor test : tests) {
if (test.isFocused()) {
focused = test;
}
}
return focused;
}
public String getAbsoluteUriToTestXmlFile() {
return absoluteUriToTestXmlFile;
}
public void setAbsoluteUriToTestXmlFile(String absoluteUriToTestXmlFile) {
this.absoluteUriToTestXmlFile = absoluteUriToTestXmlFile;
}
}
| 1,339 | 24.283019 | 79 | java |
pmd | pmd-master/pmd-test-schema/src/main/java/net/sourceforge/pmd/test/schema/RuleTestDescriptor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.test.schema;
import java.util.List;
import java.util.Properties;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.lang.LanguageVersion;
/**
* @author Clément Fournier
*/
public class RuleTestDescriptor {
private boolean disabled;
private boolean focused;
private String description;
private LanguageVersion languageVersion;
private final Properties properties = new Properties();
private final int index;
private final Rule rule;
private String code;
private int expectedProblems;
private List<Integer> expectedLineNumbers;
private List<String> expectedMessages;
private int lineNumber;
public RuleTestDescriptor(int index, Rule rule) {
this.index = index;
this.rule = rule;
this.languageVersion = rule.getLanguage().getDefaultVersion();
}
public Rule getRule() {
return rule;
}
public Properties getProperties() {
return properties;
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LanguageVersion getLanguageVersion() {
return languageVersion;
}
public void setLanguageVersion(LanguageVersion languageVersion) {
if (!languageVersion.getLanguage().equals(this.getRule().getLanguage())) {
throw new IllegalArgumentException("Invalid version " + languageVersion);
}
this.languageVersion = languageVersion;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public void recordExpectedViolations(int expectedProblems, List<Integer> expectedLineNumbers, List<String> expectedMessages) {
checkListSize(expectedProblems, expectedLineNumbers);
checkListSize(expectedProblems, expectedMessages);
this.expectedProblems = expectedProblems;
this.expectedLineNumbers = expectedLineNumbers;
this.expectedMessages = expectedMessages;
}
private void checkListSize(int expectedProblems, List<?> expectedMessages) {
if (!expectedMessages.isEmpty() && expectedProblems != expectedMessages.size()) {
throw new IllegalArgumentException(
"Expected list of size " + expectedProblems + ", got " + expectedMessages);
}
}
public int getExpectedProblems() {
return expectedProblems;
}
public int getIndex() {
return index;
}
public List<Integer> getExpectedLineNumbers() {
return expectedLineNumbers;
}
public List<String> getExpectedMessages() {
return expectedMessages;
}
public boolean isFocused() {
return focused;
}
public void setFocused(boolean focused) {
this.focused = focused;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
}
| 3,308 | 24.851563 | 130 | java |
pmd | pmd-master/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CPPTokenizerTest.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.assertEquals;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class CPPTokenizerTest extends CpdTextComparisonTest {
CPPTokenizerTest() {
super(".cpp");
}
@Override
protected String getResourcePrefix() {
return "../lang/cpp/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties props) {
CPPTokenizer tok = new CPPTokenizer();
tok.setProperties(props);
return tok;
}
@Override
public Properties defaultProperties() {
return dontSkipBlocks();
}
@Test
void testUTFwithBOM() {
Tokenizer tokenizer = newTokenizer(dontSkipBlocks());
Tokens tokens = tokenize(tokenizer, "\ufeffint start()\n{ int ret = 1;\nreturn ret;\n}\n");
assertEquals(15, tokens.size());
}
@Test
void testContinuation() {
doTest("continuation");
}
@Test
void testContinuationInIdent() {
doTest("continuation_intra_token");
}
@Test
void testContinuationBetweenTokens() {
doTest("continuation_inter_token");
}
@Test
void testUnicodeStringSupport() {
doTest("unicodeStrings");
}
@Test
void testIgnoreBetweenSpecialComments() {
doTest("specialComments");
}
@Test
void testMultiLineMacros() {
doTest("multilineMacros");
}
@Test
void testIdentifierValidChars() {
doTest("identifierChars");
}
@Test
void testWrongUnicodeInIdentifier() {
expectTokenMgrError(" void main() { int ⚜ = __; }");
}
@Test
void testTokenizerWithSkipBlocks() {
doTest("simpleSkipBlocks", "_skipDefault", skipBlocks());
}
@Test
void testTokenizerWithSkipBlocksPattern() {
doTest("simpleSkipBlocks", "_skipDebug", skipBlocks("#if debug|#endif"));
}
@Test
void testTokenizerWithoutSkipBlocks() {
doTest("simpleSkipBlocks", "_noSkip", dontSkipBlocks());
}
@Test
void testAsm() {
// ASM code containing the '@' character
doTest("asm", "", dontSkipBlocks());
}
@Test
void testPreprocessingDirectives() {
doTest("preprocessorDirectives");
}
@Test
void testLiterals() {
doTest("literals");
}
@Test
void testLexicalErrorFilename() {
expectTokenMgrError(sourceText("issue-1559"), dontSkipBlocks());
}
@Test
void testRawStringLiterals() {
doTest("issue-1784");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
@Test
void testLongListsOfNumbersAreNotIgnored() {
doTest("listOfNumbers");
}
@Test
void testLongListsOfNumbersAreIgnored() {
doTest("listOfNumbers", "_ignored", skipLiteralSequences());
}
@Test
void testLongListsOfNumbersAndIdentifiersAreIgnored() {
doTest("listOfNumbers", "_ignored_identifiers", skipIdentifierAndLiteralsSequences());
}
@Test
void testLongListsOfIdentifiersAreIgnored() {
doTest("listOfNumbers", "_ignored_identifiers", skipIdentifierSequences());
}
private static Properties skipBlocks(String skipPattern) {
return properties(true, skipPattern, false, false);
}
private static Properties skipBlocks() {
return skipBlocks(null);
}
private static Properties dontSkipBlocks() {
return properties(false, null, false, false);
}
private static Properties skipLiteralSequences() {
return properties(false, null, true, false);
}
private static Properties skipIdentifierAndLiteralsSequences() {
return properties(false, null, true, true);
}
private static Properties skipIdentifierSequences() {
return properties(false, null, false, true);
}
private static Properties properties(boolean skipBlocks, String skipPattern, boolean skipLiteralSequences, boolean skipSequences) {
Properties properties = new Properties();
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS, Boolean.toString(skipBlocks));
if (skipPattern != null) {
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS_PATTERN, skipPattern);
}
properties.setProperty(Tokenizer.OPTION_IGNORE_LITERAL_SEQUENCES, Boolean.toString(skipLiteralSequences));
properties.setProperty(Tokenizer.OPTION_IGNORE_IDENTIFIER_AND_LITERAL_SEQUENCES, Boolean.toString(skipSequences));
return properties;
}
}
| 4,719 | 24.240642 | 135 | java |
pmd | pmd-master/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.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.assertEquals;
import java.io.IOException;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.document.CpdCompat;
import net.sourceforge.pmd.lang.document.FileId;
import net.sourceforge.pmd.lang.document.TextDocument;
class CppCharStreamTest {
@NonNull
public CharStream charStreamFor(String source) throws IOException {
TextDocument textDoc = TextDocument.readOnlyString(source, FileId.UNKNOWN, CpdCompat.dummyVersion());
return CharStream.create(textDoc, new CPPTokenizer().tokenBehavior());
}
@Test
void testContinuationUnix() throws IOException {
CharStream stream = charStreamFor("a\\\nb");
assertStream(stream, "ab");
}
@Test
void testContinuationWindows() throws IOException {
// note that the \r is normalized to a \n by the TextFile
CharStream stream = charStreamFor("a\\\r\nb");
assertStream(stream, "ab");
}
@Test
void testBackup() throws IOException {
// note that the \r is normalized to a \n by the TextFile
CharStream stream = charStreamFor("a\\b\\qc");
assertStream(stream, "a\\b\\qc");
}
private void assertStream(CharStream stream, String token) throws IOException {
char c = stream.markTokenStart();
assertEquals(token.charAt(0), c);
for (int i = 1; i < token.length(); i++) {
c = stream.readChar();
assertEquals(token.charAt(i), c, token + " char at " + i + ": " + token.charAt(i) + " != " + c);
}
assertEquals(token, stream.getTokenImage());
// StringBuilder sb = new StringBuilder();
// stream.appendSuffix(sb, token.length());
// assertEquals(token, sb.toString());
}
}
| 2,029 | 32.833333 | 109 | java |
pmd | pmd-master/pmd-cpp/src/main/java/net/sourceforge/pmd/cpd/CPPTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import java.util.regex.Pattern;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.cpd.token.JavaCCTokenFilter;
import net.sourceforge.pmd.cpd.token.TokenFilter;
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.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException;
import net.sourceforge.pmd.lang.cpp.ast.CppTokenKinds;
import net.sourceforge.pmd.lang.document.TextDocument;
/**
* The C++ tokenizer.
*/
public class CPPTokenizer extends JavaCCTokenizer {
private boolean skipBlocks;
private Pattern skipBlocksStart;
private Pattern skipBlocksEnd;
private boolean ignoreIdentifierAndLiteralSeqences = false;
private boolean ignoreLiteralSequences = false;
public CPPTokenizer() {
setProperties(new Properties()); // set the defaults
}
/**
* Sets the possible options for the C++ tokenizer.
*
* @param properties the properties
* @see #OPTION_SKIP_BLOCKS
* @see #OPTION_SKIP_BLOCKS_PATTERN
* @see #OPTION_IGNORE_LITERAL_SEQUENCES
*/
public void setProperties(Properties properties) {
skipBlocks = Boolean.parseBoolean(properties.getProperty(OPTION_SKIP_BLOCKS, Boolean.TRUE.toString()));
if (skipBlocks) {
String skipBlocksPattern = properties.getProperty(OPTION_SKIP_BLOCKS_PATTERN, DEFAULT_SKIP_BLOCKS_PATTERN);
String[] split = skipBlocksPattern.split("\\|", 2);
skipBlocksStart = CppBlockSkipper.compileSkipMarker(split[0]);
if (split.length == 1) {
skipBlocksEnd = skipBlocksStart;
} else {
skipBlocksEnd = CppBlockSkipper.compileSkipMarker(split[1]);
}
}
ignoreLiteralSequences = Boolean.parseBoolean(properties.getProperty(OPTION_IGNORE_LITERAL_SEQUENCES, Boolean.FALSE.toString()));
ignoreIdentifierAndLiteralSeqences =
Boolean.parseBoolean(properties.getProperty(OPTION_IGNORE_IDENTIFIER_AND_LITERAL_SEQUENCES, Boolean.FALSE.toString()));
}
@Override
protected TokenDocumentBehavior tokenBehavior() {
return new TokenDocumentBehavior(CppTokenKinds.TOKEN_NAMES) {
@Override
public TextDocument translate(TextDocument text) throws MalformedSourceException {
if (skipBlocks) {
text = new CppBlockSkipper(text, skipBlocksStart, skipBlocksEnd).translateDocument();
}
return new CppEscapeTranslator(text).translateDocument();
}
};
}
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return CppTokenKinds.newTokenManager(sourceCode);
}
@Override
protected TokenFilter<JavaccToken> getTokenFilter(final TokenManager<JavaccToken> tokenManager) {
return new CppTokenFilter(tokenManager, ignoreLiteralSequences, ignoreIdentifierAndLiteralSeqences);
}
private static class CppTokenFilter extends JavaCCTokenFilter {
private final boolean ignoreLiteralSequences;
private final boolean ignoreIdentifierAndLiteralSeqences;
private JavaccToken discardingTokensUntil = null;
private boolean discardCurrent = false;
CppTokenFilter(final TokenManager<JavaccToken> tokenManager, final boolean ignoreLiteralSequences, final boolean ignoreIdentifierAndLiteralSeqences) {
super(tokenManager);
this.ignoreIdentifierAndLiteralSeqences = ignoreIdentifierAndLiteralSeqences;
this.ignoreLiteralSequences = ignoreLiteralSequences;
}
@Override
protected void analyzeTokens(final JavaccToken currentToken, final Iterable<JavaccToken> remainingTokens) {
discardCurrent = false;
skipSequences(currentToken, remainingTokens);
}
private void skipSequences(final JavaccToken currentToken, final Iterable<JavaccToken> remainingTokens) {
if (ignoreLiteralSequences || ignoreIdentifierAndLiteralSeqences) {
final int kind = currentToken.getKind();
if (isDiscardingToken()) {
if (currentToken == discardingTokensUntil) { // NOPMD - intentional check for reference equality
discardingTokensUntil = null;
discardCurrent = true;
}
} else if (kind == CppTokenKinds.LCURLYBRACE) {
final JavaccToken finalToken = findEndOfSequenceToDiscard(remainingTokens, ignoreIdentifierAndLiteralSeqences);
discardingTokensUntil = finalToken;
}
}
}
private static JavaccToken findEndOfSequenceToDiscard(final Iterable<JavaccToken> remainingTokens, boolean ignoreIdentifierAndLiteralSeqences) {
boolean seenAllowedToken = false;
int braceCount = 0;
for (final JavaccToken token : remainingTokens) {
switch (token.getKind()) {
case CppTokenKinds.BINARY_INT_LITERAL:
case CppTokenKinds.DECIMAL_INT_LITERAL:
case CppTokenKinds.FLOAT_LITERAL:
case CppTokenKinds.HEXADECIMAL_INT_LITERAL:
case CppTokenKinds.OCTAL_INT_LITERAL:
case CppTokenKinds.ZERO:
case CppTokenKinds.STRING:
seenAllowedToken = true;
break; // can be skipped; continue to the next token
case CppTokenKinds.ID:
// Ignore identifiers if instructed
if (ignoreIdentifierAndLiteralSeqences) {
seenAllowedToken = true;
break; // can be skipped; continue to the next token
} else {
// token not expected, other than identifier
return null;
}
case CppTokenKinds.COMMA:
break; // can be skipped; continue to the next token
case CppTokenKinds.LCURLYBRACE:
braceCount++;
break; // curly braces are allowed, as long as they're balanced
case CppTokenKinds.RCURLYBRACE:
braceCount--;
if (braceCount < 0) {
// end of the list; skip all contents
return seenAllowedToken ? 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;
}
private boolean isDiscardingToken() {
return discardingTokensUntil != null;
}
@Override
protected boolean isLanguageSpecificDiscarding() {
return isDiscardingToken() || discardCurrent;
}
}
}
| 7,478 | 41.982759 | 158 | java |
pmd | pmd-master/pmd-cpp/src/main/java/net/sourceforge/pmd/cpd/CPPLanguage.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
/**
* Defines the Language module for C/C++
*/
public class CPPLanguage extends AbstractLanguage {
/**
* Creates a new instance of {@link CPPLanguage} with the default extensions
* for c/c++ files.
*/
public CPPLanguage() {
this(System.getProperties());
}
public CPPLanguage(Properties properties) {
super("C++", "cpp", new CPPTokenizer(), ".h", ".hpp", ".hxx", ".c", ".cpp", ".cxx", ".cc", ".C");
setProperties(properties);
}
@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
((CPPTokenizer) getTokenizer()).setProperties(properties);
}
}
| 828 | 24.121212 | 105 | java |
pmd | pmd-master/pmd-cpp/src/main/java/net/sourceforge/pmd/cpd/CppEscapeTranslator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import net.sourceforge.pmd.lang.ast.impl.javacc.BackslashEscapeTranslator;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.document.TextDocument;
public class CppEscapeTranslator extends BackslashEscapeTranslator {
private static final char NEWLINE = '\n';
private static final char CARRIAGE_RETURN = '\r';
public CppEscapeTranslator(TextDocument input) {
super(input);
}
@Override
protected int handleBackslash(int maxOff, final int backSlashOff) {
int off = backSlashOff + 1;
if (input.charAt(off) == NEWLINE) {
return recordEscape(backSlashOff, off + 1, Chars.EMPTY);
} else if (input.charAt(off) == CARRIAGE_RETURN) {
off++;
if (input.charAt(off) == NEWLINE) {
return recordEscape(backSlashOff, off + 1, Chars.EMPTY);
}
}
return abortEscape(off, maxOff);
}
}
| 1,063 | 28.555556 | 79 | java |
pmd | pmd-master/pmd-cpp/src/main/java/net/sourceforge/pmd/cpd/CppBlockSkipper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.pmd.lang.ast.impl.javacc.EscapeTranslator;
import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.document.TextDocument;
/**
*
*/
class CppBlockSkipper extends EscapeTranslator {
private final Pattern skipStart;
private final Pattern skipEnd;
static Pattern compileSkipMarker(String marker) {
return Pattern.compile("^(?i)" + Pattern.quote(marker), Pattern.MULTILINE);
}
CppBlockSkipper(TextDocument original, Pattern skipStartMarker, Pattern skipEndMarker) {
super(original);
skipStart = skipStartMarker;
skipEnd = skipEndMarker;
}
@Override
protected int gobbleMaxWithoutEscape(int maxOff) throws MalformedSourceException {
Matcher start = skipStart.matcher(input).region(this.bufpos, maxOff);
if (start.find()) {
Matcher end = skipEnd.matcher(input).region(start.end(), maxOff);
if (end.find()) {
return recordEscape(start.start(), end.end(), Chars.EMPTY);
}
}
return super.gobbleMaxWithoutEscape(maxOff);
}
}
| 1,381 | 29.711111 | 92 | java |
pmd | pmd-master/pmd-groovy/src/test/java/net/sourceforge/pmd/cpd/GroovyTokenizerTest.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 GroovyTokenizerTest extends CpdTextComparisonTest {
GroovyTokenizerTest() {
super(".groovy");
}
@Override
protected String getResourcePrefix() {
return "../lang/groovy/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new GroovyTokenizer();
}
@Test
void testSample() {
doTest("sample");
}
}
| 665 | 18.588235 | 79 | java |
pmd | pmd-master/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
/**
* Language implementation for Groovy
*/
public class GroovyLanguage extends AbstractLanguage {
/**
* Creates a new Groovy Language instance.
*/
public GroovyLanguage() {
super("Groovy", "groovy", new GroovyTokenizer(), ".groovy");
}
}
| 395 | 19.842105 | 79 | java |
pmd | pmd-master/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyTokenizer.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.StringReader;
import org.codehaus.groovy.antlr.SourceInfo;
import org.codehaus.groovy.antlr.parser.GroovyLexer;
import net.sourceforge.pmd.lang.ast.TokenMgrError;
import net.sourceforge.pmd.lang.document.CpdCompat;
import net.sourceforge.pmd.lang.document.FileId;
import groovyjarjarantlr.Token;
import groovyjarjarantlr.TokenStream;
import groovyjarjarantlr.TokenStreamException;
/**
* The Groovy Tokenizer
*/
public class GroovyTokenizer implements Tokenizer {
@Override
public void tokenize(SourceCode sourceCode, Tokens tokenEntries) {
StringBuilder buffer = sourceCode.getCodeBuffer();
FileId fileId = CpdCompat.cpdCompat(sourceCode).getFileId();
GroovyLexer lexer = new GroovyLexer(new StringReader(buffer.toString()));
TokenStream tokenStream = lexer.plumb();
try {
Token token = tokenStream.nextToken();
while (token.getType() != Token.EOF_TYPE) {
String tokenText = token.getText();
int lastCol;
if (token instanceof SourceInfo) {
lastCol = ((SourceInfo) token).getColumnLast();
} else {
// fallback
lastCol = token.getColumn() + tokenText.length();
}
TokenEntry tokenEntry = new TokenEntry(tokenText, sourceCode.getFileName(), token.getLine(), token.getColumn(), lastCol);
tokenEntries.add(tokenEntry);
token = tokenStream.nextToken();
}
} catch (TokenStreamException err) {
// Wrap exceptions of the Groovy tokenizer in a TokenMgrError, so
// they are correctly handled
// when CPD is executed with the '--skipLexicalErrors' command line
// option
throw new TokenMgrError(lexer.getLine(), lexer.getColumn(), fileId, err.getMessage(), err);
} finally {
tokenEntries.add(TokenEntry.getEOF());
}
}
}
| 2,131 | 32.84127 | 137 | java |
pmd | pmd-master/pmd-perl/src/test/java/net/sourceforge/pmd/lang/perl/cpd/PerlTokenizerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.perl.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.PerlLanguage;
import net.sourceforge.pmd.cpd.Tokenizer;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
/**
*
*/
class PerlTokenizerTest extends CpdTextComparisonTest {
PerlTokenizerTest() {
super(".pl");
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new PerlLanguage().getTokenizer();
}
@Test
void testSample() {
doTest("sample");
}
}
| 666 | 18.617647 | 79 | java |
pmd | pmd-master/pmd-perl/src/main/java/net/sourceforge/pmd/cpd/PerlLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
public class PerlLanguage extends AbstractLanguage {
public PerlLanguage() {
super("Perl", "perl", new AnyTokenizer("#"), ".pm", ".pl", ".t");
}
}
| 286 | 22.916667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/LanguageVersionDiscovererTest.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 java.io.File;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class LanguageVersionDiscovererTest extends AbstractPLSQLParserTst {
/**
* Test on PLSQL file with default version
*/
@Test
void testPlsql() {
LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD);
File plsqlFile = new File("/path/to/MY_PACKAGE.sql");
LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(plsqlFile);
assertEquals(plsql.getLanguage().getDefaultVersion(), languageVersion,
"LanguageVersion must be PLSQL!");
}
}
| 1,025 | 30.090909 | 99 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/RuleSetFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
/**
* Test plsql's rulesets
*/
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
// no additional tests yet
}
| 314 | 20 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/LanguageVersionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
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(PLSQLLanguageModule.NAME, PLSQLLanguageModule.TERSE_NAME, "21c",
getLanguage(PLSQLLanguageModule.NAME).getDefaultVersion()));
}
}
| 548 | 27.894737 | 112 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/PlsqlParsingHelper.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
public class PlsqlParsingHelper extends BaseParsingHelper<PlsqlParsingHelper, ASTInput> {
/** This runs all processing stages when parsing. */
public static final PlsqlParsingHelper DEFAULT = new PlsqlParsingHelper(Params.getDefault());
private PlsqlParsingHelper(Params params) {
super(PLSQLLanguageModule.NAME, ASTInput.class, params);
}
@Override
protected PlsqlParsingHelper clone(Params params) {
return new PlsqlParsingHelper(params);
}
}
| 737 | 27.384615 | 97 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/AbstractPLSQLParserTst.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
public abstract class AbstractPLSQLParserTst {
protected final PlsqlParsingHelper plsql = PlsqlParsingHelper.DEFAULT.withResourceContext(getClass());
}
| 288 | 23.083333 | 106 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/PLSQLXPathRuleTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.lang.rule.XPathRule;
import net.sourceforge.pmd.lang.rule.xpath.XPathVersion;
/**
* Tests to use XPath rules with PLSQL.
*/
class PLSQLXPathRuleTest extends AbstractPLSQLParserTst {
private static final String SOURCE =
"create or replace\n" + "package pkg_xpath_problem\n" + "AS\n" + " PROCEDURE pkg_minimal\n" + " IS\n"
+ " a_variable VARCHAR2(1);\n" + " BEGIN \n" + " --PRAGMA INLINE(output,'YES');\n"
+ " a_variable := 'Y' ;\n" + " END ;\n" + "end pkg_xpath_problem;\n" + "/\n";
/**
* See https://sourceforge.net/p/pmd/bugs/1166/
*/
@Test
void testXPathRule1() {
testOnVersion(XPathVersion.XPATH_1_0);
}
/**
* See https://sourceforge.net/p/pmd/bugs/1166/
*/
@Test
void testXPathRule1Compatibility() {
testOnVersion(XPathVersion.XPATH_1_0_COMPATIBILITY);
}
/**
* See https://sourceforge.net/p/pmd/bugs/1166/
*/
@Test
void testXPathRule2() {
testOnVersion(XPathVersion.XPATH_2_0);
}
private void testOnVersion(XPathVersion xpath10) {
XPathRule rule = plsql.newXpathRule("//PrimaryPrefix", xpath10);
Report report = plsql.executeRule(rule, SOURCE);
assertEquals(2, report.getViolations().size());
}
}
| 1,604 | 27.157895 | 115 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ExecuteImmediateBulkCollectTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.plsql.PlsqlParsingHelper;
class ExecuteImmediateBulkCollectTest extends BaseTreeDumpTest {
ExecuteImmediateBulkCollectTest() {
super(new RelevantAttributePrinter(), ".pls");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return PlsqlParsingHelper.DEFAULT.withResourceContext(getClass());
}
@Test
void testExecuteImmediateBulkCollect1() {
doTest("ExecuteImmediateBulkCollect1");
}
@Test
void testExecuteImmediateBulkCollect2() {
doTest("ExecuteImmediateBulkCollect2");
}
@Test
void testExecuteImmediateBulkCollect3() {
doTest("ExecuteImmediateBulkCollect3");
}
}
| 1,062 | 25.575 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/CursorWithWithTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class CursorWithWithTest extends AbstractPLSQLParserTst {
@Test
void parseCursorWithWith() {
ASTInput input = plsql.parseResource("CursorWithWith.pls");
ASTCursorUnit cursor = input.getFirstDescendantOfType(ASTCursorUnit.class);
ASTSelectStatement select = (ASTSelectStatement) cursor.getChild(1);
ASTWithClause with = (ASTWithClause) select.getChild(0);
ASTName queryName = (ASTName) with.getChild(0);
assertEquals("risk_set", queryName.getImage());
}
}
| 811 | 31.48 | 83 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/AnonymousBlockTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class AnonymousBlockTest extends AbstractPLSQLParserTst {
@Test
void parseCursorInsideProcAnonymousBlock() {
plsql.parseResource("AnonymousBlock1.sql");
}
@Test
void parseCursorInsideAnonymousBlock() {
plsql.parseResource("AnonymousBlock2.sql");
}
}
| 525 | 21.869565 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/JoinClauseTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
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.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class JoinClauseTest extends AbstractPLSQLParserTst {
@Test
void testInnerCrossJoin() {
ASTInput input = plsql.parseResource("InnerCrossJoin.pls");
List<ASTInnerCrossJoinClause> joins = input.findDescendantsOfType(ASTInnerCrossJoinClause.class);
assertEquals(1, joins.size());
assertTrue(joins.get(0).isCross());
assertFalse(joins.get(0).isNatural());
}
@Test
void testInnerNaturalJoin() {
ASTInput input = plsql.parseResource("InnerNaturalJoin.pls");
List<ASTInnerCrossJoinClause> joins = input.findDescendantsOfType(ASTInnerCrossJoinClause.class);
assertEquals(2, joins.size());
assertFalse(joins.get(0).isCross());
assertTrue(joins.get(0).isNatural());
}
@Test
void testInnerJoinUsing() {
ASTInput input = plsql.parseResource("InnerJoinUsing.pls");
List<ASTInnerCrossJoinClause> joins = input.findDescendantsOfType(ASTInnerCrossJoinClause.class);
assertEquals(3, joins.size());
assertFalse(joins.get(0).isCross());
assertFalse(joins.get(0).isNatural());
List<ASTColumn> columns = joins.get(0).findChildrenOfType(ASTColumn.class);
assertEquals(1, columns.size());
assertEquals("department_id", columns.get(0).getImage());
}
@Test
void testOuterJoinUsing() {
ASTInput input = plsql.parseResource("OuterJoinUsing.pls");
List<ASTOuterJoinClause> joins = input.findDescendantsOfType(ASTOuterJoinClause.class);
assertEquals(1, joins.size());
ASTOuterJoinType type = joins.get(0).getFirstChildOfType(ASTOuterJoinType.class);
assertEquals(ASTOuterJoinType.Type.FULL, type.getType());
List<ASTColumn> columns = joins.get(0).findChildrenOfType(ASTColumn.class);
assertEquals(1, columns.size());
assertEquals("department_id", columns.get(0).getImage());
}
@Test
void testRightOuterJoin() {
ASTInput input = plsql.parseResource("RightOuterJoin.pls");
List<ASTOuterJoinClause> joins = input.findDescendantsOfType(ASTOuterJoinClause.class);
assertEquals(2, joins.size());
ASTOuterJoinType type = joins.get(0).getFirstChildOfType(ASTOuterJoinType.class);
assertEquals(ASTOuterJoinType.Type.RIGHT, type.getType());
}
@Test
void testLeftOuterJoin() {
ASTInput input = plsql.parseResource("LeftOuterJoin.pls");
List<ASTOuterJoinClause> joins = input.findDescendantsOfType(ASTOuterJoinClause.class);
assertEquals(2, joins.size());
ASTOuterJoinType type = joins.get(0).getFirstChildOfType(ASTOuterJoinType.class);
assertEquals(ASTOuterJoinType.Type.LEFT, type.getType());
List<ASTSelectStatement> selects = input.findDescendantsOfType(ASTSelectStatement.class);
assertEquals(2, selects.size());
assertTrue(selects.get(0).getFromClause().getChild(0) instanceof ASTJoinClause);
assertTrue(selects.get(1).getFromClause().getChild(0) instanceof ASTJoinClause);
}
@Test
void testNaturalRightOuterJoin() {
ASTInput input = plsql.parseResource("NaturalRightOuterJoin.pls");
List<ASTOuterJoinClause> joins = input.findDescendantsOfType(ASTOuterJoinClause.class);
assertEquals(1, joins.size());
ASTOuterJoinType type = joins.get(0).getFirstChildOfType(ASTOuterJoinType.class);
assertEquals(ASTOuterJoinType.Type.RIGHT, type.getType());
assertTrue(joins.get(0).isNatural());
}
@Test
void testOuterJoinPartitioned() {
ASTInput input = plsql.parseResource("OuterJoinPartitioned.pls");
List<ASTOuterJoinClause> joins = input.findDescendantsOfType(ASTOuterJoinClause.class);
assertEquals(1, joins.size());
ASTOuterJoinType type = joins.get(0).getFirstChildOfType(ASTOuterJoinType.class);
assertEquals(ASTOuterJoinType.Type.RIGHT, type.getType());
assertNotNull(joins.get(0).getFirstChildOfType(ASTQueryPartitionClause.class));
}
@Test
void testFullOuterJoin() {
plsql.parseResource("FullOuterJoin.pls");
}
@Test
void testInnerJoinSubquery() {
plsql.parseResource("InnerJoinSubquery.pls");
}
@Test
void testJoinOperator() {
ASTInput input = plsql.parseResource("JoinOperator.pls");
List<ASTOuterJoinExpression> expressions = input.findDescendantsOfType(ASTOuterJoinExpression.class);
assertEquals(4, expressions.size());
assertEquals("h.opp_id", expressions.get(3).getImage());
}
}
| 5,058 | 40.130081 | 109 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ViewTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ViewTest extends AbstractPLSQLParserTst {
@Test
void parseCreateViewIssue981() {
plsql.parseResource("ViewIssue981.pls");
}
@Test
void parseCreateView() {
plsql.parseResource("CreateViewWithSubquery.pls");
}
@Test
void parseCreateViewWithoutSemicolon() {
plsql.parseResource("QueryWithoutSemicolon.sql");
}
}
| 611 | 20.857143 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/CursorForLoopTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class CursorForLoopTest extends AbstractPLSQLParserTst {
@Test
void parseCursorForLoopSimple() {
ASTInput input = plsql.parseResource("CursorForLoopSimple.pls");
ASTCursorForLoopStatement forloop = input.getFirstDescendantOfType(ASTCursorForLoopStatement.class);
assertNotNull(forloop);
ASTForIndex forindex = forloop.getFirstChildOfType(ASTForIndex.class);
assertNotNull(forindex);
assertEquals("someone", forindex.getImage());
}
@Test
void parseCursorForLoopNested() {
ASTInput input = plsql.parseResource("CursorForLoopNested.pls");
ASTCursorForLoopStatement forloop = input.getFirstDescendantOfType(ASTCursorForLoopStatement.class);
assertNotNull(forloop);
ASTForIndex forindex = forloop.getFirstChildOfType(ASTForIndex.class);
assertNotNull(forindex);
assertEquals("c_cmp", forindex.getImage());
ASTCursorForLoopStatement forloop2 = forloop.getFirstDescendantOfType(ASTCursorForLoopStatement.class);
ASTForIndex forindex2 = forloop2.getFirstChildOfType(ASTForIndex.class);
assertEquals("c_con", forindex2.getImage());
ASTCursorForLoopStatement forloop3 = forloop2.getFirstDescendantOfType(ASTCursorForLoopStatement.class);
ASTForIndex forindex3 = forloop3.getFirstChildOfType(ASTForIndex.class);
assertEquals("c_pa", forindex3.getImage());
}
@Test
void parseCursorForLoop1047a() {
ASTInput input = plsql.parseResource("CursorForLoop1047a.pls");
assertNotNull(input);
}
@Test
void parseCursorForLoop1047b() {
ASTInput input = plsql.parseResource("CursorForLoop1047b.pls");
assertNotNull(input);
}
@Test
void parseCursorForLoop681() {
ASTInput input = plsql.parseResource("CursorForLoop681.pls");
assertNotNull(input);
}
}
| 2,242 | 35.177419 | 112 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTFetchStatementTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.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.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ASTFetchStatementTest extends AbstractPLSQLParserTst {
@Test
void testBulkCollectLimit() {
ASTInput input = plsql.parseResource("FetchStatementBulkCollectLimit.pls");
List<ASTFetchStatement> fetchStatements = input.findDescendantsOfType(ASTFetchStatement.class);
assertEquals(1, fetchStatements.size());
ASTFetchStatement fetch = fetchStatements.get(0);
assertTrue(fetch.isBulkCollect());
assertTrue(fetch.isLimit());
}
@Test
void testFetch() {
ASTInput input = plsql.parseResource("FetchStatement.pls");
List<ASTFetchStatement> fetchStatements = input.findDescendantsOfType(ASTFetchStatement.class);
assertEquals(1, fetchStatements.size());
ASTFetchStatement fetch = fetchStatements.get(0);
assertFalse(fetch.isBulkCollect());
assertFalse(fetch.isLimit());
}
}
| 1,327 | 33.051282 | 103 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/StringLiteralsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class StringLiteralsTest extends AbstractPLSQLParserTst {
@Test
void parseStringLiterals() throws Exception {
ASTInput input = plsql.parseResource("StringLiterals.pls");
List<ASTStringLiteral> strings = input.findDescendantsOfType(ASTStringLiteral.class);
assertEquals(20, strings.size());
assertString("'Hello'", "Hello", 0, strings);
assertString("N'nchar literal'", "nchar literal", 4, strings);
assertString("nQ'[ab']cd]'", "ab']cd", 11, strings);
assertString("Q'{SELECT * FROM employees WHERE last_name = 'Smith';}'",
"SELECT * FROM employees WHERE last_name = 'Smith';", 13, strings);
assertString("q'{\n" + " also multiple\n" + " lines\n" + " }'",
"\n" + " also multiple\n" + " lines\n" + " ", 15, strings);
}
@Test
void parseMultilineVarchar() throws Exception {
ASTInput input = plsql.parseResource("MultilineVarchar.pls");
List<ASTStringLiteral> strings = input.findDescendantsOfType(ASTStringLiteral.class);
assertEquals(1, strings.size());
assertTrue(normalizeEol(strings.get(0).getString()).startsWith("\ncreate or replace and"));
}
private static void assertString(String quoted, String plain, int index, List<ASTStringLiteral> strings) {
assertEquals(quoted, normalizeEol(strings.get(index).getImage()));
assertEquals(plain, normalizeEol(strings.get(index).getString()));
}
private static String normalizeEol(String s) {
return s.replaceAll("\r\n|\n\r|\n|\r", "\n");
}
}
| 1,977 | 37.784314 | 110 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/FunctionsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class FunctionsTest extends AbstractPLSQLParserTst {
@Test
void parseTrimCall() {
plsql.parseResource("TrimFunction.pls");
}
@Test
void parseSelectExtractExpression() {
plsql.parseResource("ExtractExpressions.pls");
}
@Test
void parseXMLExpression() {
plsql.parseResource("XMLFunctions.pls");
}
}
| 593 | 20.214286 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectIntoWithGroupByTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectIntoWithGroupByTest extends AbstractPLSQLParserTst {
@Test
void testExample1() {
ASTInput input = plsql.parseResource("SelectIntoWithGroupBy1.pls");
ASTGroupByClause groupByClause = input.getFirstDescendantOfType(ASTGroupByClause.class);
assertNotNull(groupByClause);
}
@Test
void testExample2() {
ASTInput input = plsql.parseResource("SelectIntoWithGroupBy2.pls");
ASTGroupByClause groupByClause = input.getFirstDescendantOfType(ASTGroupByClause.class);
assertNotNull(groupByClause);
}
@Test
void testExample3WithCube() {
ASTInput input = plsql.parseResource("SelectIntoWithGroupBy3.pls");
ASTRollupCubeClause cubeClause = input.getFirstDescendantOfType(ASTRollupCubeClause.class);
assertNotNull(cubeClause);
assertEquals("CUBE", cubeClause.getImage());
}
@Test
void testExample4WithGroupingSets() {
ASTInput input = plsql.parseResource("SelectIntoWithGroupBy4.pls");
ASTGroupingSetsClause groupingSetsClause = input.getFirstDescendantOfType(ASTGroupingSetsClause.class);
assertNotNull(groupingSetsClause);
List<ASTFromClause> fromClauses = input.findDescendantsOfType(ASTFromClause.class);
assertEquals(1, fromClauses.size());
assertEquals(5, fromClauses.get(0).getNumChildren());
}
}
| 1,761 | 33.54902 | 111 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/TriggerTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class TriggerTest extends AbstractPLSQLParserTst {
/**
* Parsing a trigger should not result in a NPE.
*
* @see <a href="https://github.com/pmd/pmd/issues/2325">#2325 [plsql] NullPointerException while running parsing test for CREATE TRIGGER</a>
*/
@Test
void parseCreateTrigger() {
ASTInput input = plsql.parseResource("TriggerUnit.pls");
PLSQLNode trigger = input.getChild(0);
assertEquals(ASTTriggerUnit.class, trigger.getClass());
assertNotNull(trigger.getScope());
}
}
| 901 | 28.096774 | 145 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/IfStatementTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class IfStatementTest extends AbstractPLSQLParserTst {
@Test
void parseIfWithElseIf() throws Exception {
String code = "BEGIN\nIF 1 = 1 THEN null;\nELSIF (2 = 2) THEN null;\nELSE null;\nEND IF;\nEND;\n/\n";
ASTInput input = plsql.parse(code);
assertNotNull(input);
}
}
| 602 | 26.409091 | 109 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/PlsqlTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.plsql.PlsqlParsingHelper;
class PlsqlTreeDumpTest extends BaseTreeDumpTest {
PlsqlTreeDumpTest() {
super(new RelevantAttributePrinter(), ".pls");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return PlsqlParsingHelper.DEFAULT.withResourceContext(getClass());
}
@Test
void sqlPlusLexicalVariables() {
doTest("SqlPlusLexicalVariablesIssue195");
}
@Test
void parseParsingExclusion() {
doTest("ParsingExclusion");
}
@Test
void parseOpenForStatement() {
doTest("OpenForStatement");
}
@Test
void parseSelectIntoAssociativeArrayType() {
doTest("SelectIntoArray");
}
}
| 1,082 | 23.066667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectHierarchicalTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectHierarchicalTest extends AbstractPLSQLParserTst {
@Test
void parseSelectHierarchicalQueries() {
plsql.parseResource("SelectHierarchical.pls");
}
}
| 413 | 22 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTCompoundConditionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ASTCompoundConditionTest extends AbstractPLSQLParserTst {
@Test
void testParseType() {
ASTInput input = plsql.parse("BEGIN SELECT COUNT(1) INTO MY_TABLE FROM USERS_TABLE WHERE user_id = 1 AnD user_id = 2; END;");
List<ASTCompoundCondition> compoundConditions = input.findDescendantsOfType(ASTCompoundCondition.class);
assertFalse(compoundConditions.isEmpty());
assertEquals("AND", compoundConditions.get(0).getType());
}
}
| 853 | 31.846154 | 133 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/DeleteStatementTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class DeleteStatementTest extends AbstractPLSQLParserTst {
@Test
void parseDeleteStatementExample() {
ASTInput input = plsql.parseResource("DeleteStatementExample.pls");
List<ASTDeleteStatement> deleteStatements = input.findDescendantsOfType(ASTDeleteStatement.class);
assertEquals(3, deleteStatements.size());
assertEquals("product_descriptions", deleteStatements.get(0).getChild(0)
.getFirstChildOfType(ASTTableName.class).getImage());
}
}
| 875 | 31.444444 | 121 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/OrderByExpressionsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class OrderByExpressionsTest extends AbstractPLSQLParserTst {
@Test
void parseOrderByExpression() {
plsql.parseResource("OrderByExpression.pls");
}
}
| 404 | 21.5 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/CreateTableTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class CreateTableTest extends AbstractPLSQLParserTst {
@Test
void parseCreateTable() {
ASTInput input = plsql.parseResource("CreateTable.pls");
// 5th column of first table statement has a inline constraint of type check
ASTTableColumn columnStatus = input.findChildrenOfType(ASTTable.class).get(0).findChildrenOfType(ASTTableColumn.class).get(4);
assertEquals("status", columnStatus.getFirstChildOfType(ASTID.class).getImage());
assertEquals(ConstraintType.CHECK, columnStatus.getFirstChildOfType(ASTInlineConstraint.class).getType());
}
@Test
void parseCreateOrganizedTable() {
plsql.parseResource("CreateOrganizedTable.pls");
}
}
| 1,003 | 32.466667 | 134 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/UpdateStatementTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class UpdateStatementTest extends AbstractPLSQLParserTst {
@Test
void parseUpdateStatementExample() {
ASTInput input = plsql.parseResource("UpdateStatementExample.pls");
List<ASTUpdateStatement> updateStatements = input.findDescendantsOfType(ASTUpdateStatement.class);
assertEquals(2, updateStatements.size());
assertEquals(2, updateStatements.get(1).getFirstChildOfType(ASTUpdateSetClause.class)
.findChildrenOfType(ASTColumn.class).size());
}
@Test
void parseUpdateStatementExample2() {
ASTInput input = plsql.parseResource("UpdateStatementExample2.pls");
assertNotNull(input);
}
@Test
void parseUpdateStatementRef() {
ASTInput input = plsql.parseResource("UpdateStatementRef.pls");
assertNotNull(input);
}
}
| 1,210 | 30.868421 | 106 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/XMLElementTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class XMLElementTest extends AbstractPLSQLParserTst {
@Test
void testParseXMLElement() {
ASTInput input = plsql.parseResource("XMLElement.pls");
List<ASTXMLElement> xmlelements = input.findDescendantsOfType(ASTXMLElement.class);
assertEquals(10, xmlelements.size());
assertEquals("\"Emp\"", xmlelements.get(0).getFirstChildOfType(ASTID.class).getImage());
assertTrue(xmlelements.get(3).getChild(1) instanceof ASTXMLAttributesClause);
}
}
| 869 | 31.222222 | 96 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTSqlStatementTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ASTSqlStatementTest extends AbstractPLSQLParserTst {
@Test
void testCommit() {
ASTInput input = plsql.parseResource("CommitStatement.pls");
List<ASTSqlStatement> sqlStatements = input.findDescendantsOfType(ASTSqlStatement.class);
assertEquals(1, sqlStatements.size());
assertType(sqlStatements, 0, ASTSqlStatement.Type.COMMIT);
}
@Test
void testRollback() {
ASTInput input = plsql.parseResource("RollbackStatement.pls");
List<ASTSqlStatement> sqlStatements = input.findDescendantsOfType(ASTSqlStatement.class);
assertEquals(1, sqlStatements.size());
assertType(sqlStatements, 0, ASTSqlStatement.Type.ROLLBACK);
}
@Test
void testSavepoint() {
ASTInput input = plsql.parseResource("SavepointStatement.pls");
List<ASTSqlStatement> sqlStatements = input.findDescendantsOfType(ASTSqlStatement.class);
assertEquals(2, sqlStatements.size());
assertType(sqlStatements, 0, ASTSqlStatement.Type.SAVEPOINT);
assertType(sqlStatements, 1, ASTSqlStatement.Type.ROLLBACK);
}
@Test
void testSetTransaction() {
ASTInput input = plsql.parseResource("SetTransactionStatement.pls");
List<ASTSqlStatement> sqlStatements = input.findDescendantsOfType(ASTSqlStatement.class);
assertEquals(3, sqlStatements.size());
assertType(sqlStatements, 0, ASTSqlStatement.Type.COMMIT);
assertType(sqlStatements, 1, ASTSqlStatement.Type.SET_TRANSACTION);
assertType(sqlStatements, 2, ASTSqlStatement.Type.COMMIT);
}
private void assertType(List<ASTSqlStatement> sqlStatements, int index, ASTSqlStatement.Type expectedType) {
assertEquals(expectedType, sqlStatements.get(index).getType());
}
}
| 2,102 | 36.553571 | 112 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/XMLTableTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class XMLTableTest extends AbstractPLSQLParserTst {
@Test
void testParseXMLTable() {
ASTInput node = plsql.parseResource("XMLTable.pls");
List<ASTFunctionCall> functions = node.findDescendantsOfType(ASTFunctionCall.class);
ASTFunctionCall xmlforest = functions.get(functions.size() - 1);
assertEquals("XMLFOREST", xmlforest.getImage());
assertEquals("e.employee_id", xmlforest.getChild(1).getImage());
assertEquals("foo", xmlforest.getChild(2).getImage());
assertTrue(xmlforest.getChild(2) instanceof ASTID);
assertEquals("e.last_name", xmlforest.getChild(3).getImage());
assertEquals("last_name", xmlforest.getChild(4).getImage());
assertTrue(xmlforest.getChild(4) instanceof ASTID);
assertEquals("e.salary", xmlforest.getChild(5).getImage());
assertEquals(6, xmlforest.getNumChildren());
}
}
| 1,282 | 35.657143 | 92 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ParenthesisGroupTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.plsql.PlsqlParsingHelper;
class ParenthesisGroupTest extends BaseTreeDumpTest {
ParenthesisGroupTest() {
super(new RelevantAttributePrinter(), ".pls");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return PlsqlParsingHelper.DEFAULT.withResourceContext(getClass());
}
@Test
void parseParenthesisGroup0() {
doTest("ParenthesisGroup0");
}
@Test
void parseParenthesisGroup1() {
doTest("ParenthesisGroup1");
}
@Test
void parseParenthesisGroup2() {
doTest("ParenthesisGroup2");
}
}
| 978 | 22.878049 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/CursorAttributesTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class CursorAttributesTest extends AbstractPLSQLParserTst {
@Test
void parseCursorWithAttribute() {
ASTInput input = plsql.parseResource("CursorAttributes.pls");
ASTExpression exp = input.getFirstDescendantOfType(ASTIfStatement.class).getFirstChildOfType(ASTExpression.class);
assertEquals("TestSearch%notfound", exp.getImage());
}
@Test
void parseImplicitCursorAttributeBulkExceptions() {
plsql.parseResource("CursorAttributesBulkExceptions.pls");
}
}
| 807 | 27.857143 | 122 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/RecordTypeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class RecordTypeTest extends AbstractPLSQLParserTst {
@Test
void parseRecordType() {
plsql.parseResource("RecordType.pls");
}
}
| 382 | 20.277778 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/LexicalParametersTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class LexicalParametersTest extends AbstractPLSQLParserTst {
@Test
void parseLexicalParameters() {
plsql.parseResource("LexicalParameters.sql");
}
}
| 403 | 21.444444 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/WhereClauseTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class WhereClauseTest extends AbstractPLSQLParserTst {
@Test
void testFunctionCall() {
ASTInput input = plsql.parseResource("WhereClauseFunctionCall.pls");
List<ASTSelectIntoStatement> selectStatements = input.findDescendantsOfType(ASTSelectIntoStatement.class);
assertEquals(4, selectStatements.size());
ASTFunctionCall functionCall = selectStatements.get(0).getFirstDescendantOfType(ASTFunctionCall.class);
assertEquals("UPPER", functionCall.getImage());
ASTFunctionCall functionCall2 = selectStatements.get(2).getFirstDescendantOfType(ASTFunctionCall.class);
assertEquals("utils.get_colname", functionCall2.getImage());
}
@Test
void testLikeCondition() {
plsql.parseResource("WhereClauseLike.pls");
}
@Test
void testNullCondition() {
plsql.parseResource("WhereClauseIsNull.pls");
}
@Test
void testBetweenCondition() {
plsql.parseResource("WhereClauseBetween.pls");
}
@Test
void testInCondition() {
plsql.parseResource("WhereClauseIn.pls");
}
@Test
void testIsOfTypeCondition() {
plsql.parseResource("WhereClauseIsOfType.pls");
}
@Test
void testConcatenationOperator() {
plsql.parseResource("WhereClauseConcatenation.pls");
}
@Test
void testExistsCondition() {
plsql.parseResource("WhereClauseExists.pls");
}
@Test
void testMultisetCondition() {
plsql.parseResource("WhereClauseMultiset.pls");
}
@Test
void testRegexpLikeCondition() {
ASTInput input = plsql.parseResource("WhereClauseRegexpLike.pls");
List<ASTRegexpLikeCondition> regexps = input.findDescendantsOfType(ASTRegexpLikeCondition.class);
assertEquals(3, regexps.size());
assertEquals("last_name", regexps.get(1).getSourceChar().getImage());
assertEquals("'([aeiou])\\1'", regexps.get(1).getPattern().getImage());
assertEquals("'i'", regexps.get(1).getMatchParam());
}
@Test
void testSubqueries() {
plsql.parseResource("WhereClauseSubqueries.pls");
}
@Test
void testParentheses() {
plsql.parseResource("WhereClauseParens.pls");
}
@Test
void testCurrentOf() {
plsql.parseResource("WhereCurrentOf.pls");
}
}
| 2,651 | 26.915789 | 114 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/TrimWithRecordTypeTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class TrimWithRecordTypeTest extends AbstractPLSQLParserTst {
@Test
void parseTrimWithRecordType() {
plsql.parseResource("TrimWithRecordType.pls");
}
}
| 406 | 21.611111 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/MultipleDDLStatementsTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class MultipleDDLStatementsTest extends AbstractPLSQLParserTst {
@Test
void parseDDLCommands() throws Exception {
ASTInput input = plsql.parseResource("DDLCommands.sql");
List<ASTDDLCommand> ddlcommands = input.findDescendantsOfType(ASTDDLCommand.class);
assertEquals(6, ddlcommands.size());
List<ASTComment> comments = input.findDescendantsOfType(ASTComment.class);
assertEquals(5, comments.size());
assertEquals("'abbreviated job title'", comments.get(0).getFirstChildOfType(ASTStringLiteral.class).getImage());
}
}
| 897 | 32.259259 | 120 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectExpressionsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectExpressionsTest extends AbstractPLSQLParserTst {
@Test
void parseSelectExpression() {
plsql.parseResource("SelectExpressions.pls");
}
@Test
void parseSelectSimpleExpression() {
ASTInput input = plsql.parseResource("SelectSimpleExpression.pls");
assertNotNull(input);
List<ASTSimpleExpression> simpleExpressions = input.findDescendantsOfType(ASTSimpleExpression.class);
assertEquals(1, simpleExpressions.size());
ASTSimpleExpression exp = simpleExpressions.get(0);
assertEquals("e.first_name", exp.getImage());
assertEquals(2, exp.getNumChildren());
assertEquals(ASTTableName.class, exp.getChild(0).getClass());
assertEquals(ASTColumn.class, exp.getChild(1).getClass());
}
@Test
void parseSelectCount() {
plsql.parseResource("SelectCount.pls");
}
@Test
void parseSelectSubqueryExpression() {
plsql.parseResource("SelectSubqueryExpressions.pls");
}
}
| 1,391 | 28.617021 | 109 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SlashAsDivisionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SlashAsDivisionTest extends AbstractPLSQLParserTst {
@Test
void parseSlashAsDivision() {
plsql.parseResource("SlashAsDivision.sql");
}
}
| 398 | 20 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectUnionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectUnionTest extends AbstractPLSQLParserTst {
@Test
void parseSelectUnion() {
plsql.parseResource("SelectUnion.pls");
}
}
| 386 | 19.368421 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/AllPlsqlAstTreeDumpTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
@Suite
@SelectClasses({
PlsqlTreeDumpTest.class,
ParenthesisGroupTest.class,
ExecuteImmediateBulkCollectTest.class
})
class AllPlsqlAstTreeDumpTest {
}
| 394 | 19.789474 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectIntoStatementTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectIntoStatementTest extends AbstractPLSQLParserTst {
@Test
void testParsingComplex() {
plsql.parseResource("SelectIntoStatement.pls");
}
@Test
void testParsingExample1() {
plsql.parseResource("SelectIntoStatementExample1.pls");
}
@Test
void testParsingExample2() {
plsql.parseResource("SelectIntoStatementExample2.pls");
}
@Test
void testParsingExample3() {
plsql.parseResource("SelectIntoStatementExample3.pls");
}
@Test
void testParsingExample4() {
plsql.parseResource("SelectIntoStatementExample4.pls");
}
@Test
void testParsingExample5() {
plsql.parseResource("SelectIntoStatementExample5.pls");
}
@Test
void testParsingExample6Invalid() {
assertThrows(ParseException.class, () -> plsql.parseResource("SelectIntoStatementExample6Invalid.pls"));
}
@Test
void testParsingWithFunctionCall() {
plsql.parseResource("SelectIntoStatementFunctionCall.pls");
}
@Test
void testParsingIntoRecordField() {
plsql.parseResource("SelectIntoStatementRecordField.pls");
}
}
| 1,507 | 23.721311 | 112 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/TableCollectionExpressionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class TableCollectionExpressionTest extends AbstractPLSQLParserTst {
@Test
void testExamples() {
plsql.parseResource("TableCollectionExpressionExamples.pls");
}
@Test
void testIssue1526() {
plsql.parseResource("TableCollectionExpressionIssue1526.pls");
}
}
| 532 | 22.173913 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpressionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ASTExtractExpressionTest extends AbstractPLSQLParserTst {
@Test
void testXml() {
ASTInput unit = plsql.parse("SELECT warehouse_name, EXTRACT(warehouse_spec, '/Warehouse/Docks', "
+ "'xmlns:a=\"http://warehouse/1\" xmlns:b=\"http://warehouse/2\"') \"Number of Docks\" "
+ " FROM warehouses WHERE warehouse_spec IS NOT NULL;");
ASTExtractExpression extract = unit.getFirstDescendantOfType(ASTExtractExpression.class);
assertTrue(extract.isXml());
assertEquals("/Warehouse/Docks", extract.getXPath());
assertEquals("xmlns:a=\"http://warehouse/1\" xmlns:b=\"http://warehouse/2\"", extract.getNamespace());
}
}
| 1,050 | 37.925926 | 110 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/PLSQLParserTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class PLSQLParserTest extends AbstractPLSQLParserTst {
@Test
void testExceptions() {
plsql.parse("CREATE OR REPLACE PROCEDURE bar IS BEGIN" + " doSomething;" + " EXCEPTION"
+ " WHEN FooException THEN" + " doSomethingElse;" + " WHEN OTHERS THEN"
+ " doSomethingElse;" + "END;");
}
/**
* See https://sourceforge.net/p/pmd/bugs/1167/
*/
@Test
void testBOM() {
plsql.parse("\ufeff" + "CREATE OR REPLACE PROCEDURE bar IS BEGIN" + " doSomething;" + " EXCEPTION"
+ " WHEN FooException THEN" + " doSomethingElse;" + " WHEN OTHERS THEN"
+ " doSomethingElse;" + "END;");
}
@Test
void testBug1531() {
assertTimeout(Duration.of(5, ChronoUnit.SECONDS), () ->
plsql.parse("create or replace force view oxa.o_xa_function_role_types as\n"
+ "select \"CFT_ID\",\"CFR_ID\",\"CFT_NAME\",\"TCN\",\"LOG_MODULE\",\"LOG_USER\",\"LOG_DATE\",\"LOG_TIME\" from crm_function_role_types\n"
+ "/"));
}
@Test
void testBug1527() {
plsql.parseResource("InlinePragmaProcError.pls");
}
@Test
void testBug1520IsOfType() {
plsql.parseResource("IsOfType.pls");
}
@Test
void testBug1520Using() {
plsql.parseResource("Using.pls");
}
@Test
void testSingleLineSelect() {
plsql.parseResource("SingleLineSelect.pls");
}
@Test
void testMultiLineSelect() {
plsql.parseResource("MultiLineSelect.pls");
}
@Test
void testIsNull() {
plsql.parseResource("IsNull.pls");
}
@Test
void testCodingStyleExample() {
plsql.parseResource("CodingStyleExample.pls");
}
@Test
void testCaseIssue1454() {
plsql.parseResource("CaseIssue1454.pls");
}
@Test
void testRelationalOperators() {
// https://github.com/pmd/pmd/issues/3746
plsql.parseResource("RelationalOperators.pls");
}
@Test
void testExecuteImmediateIssue3106() {
plsql.parseResource("ExecuteImmediateIssue3106.pls");
}
}
| 2,585 | 26.510638 | 165 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ExecuteImmediateTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ExecuteImmediateTest extends AbstractPLSQLParserTst {
@Test
void parseExecuteImmediate1047a() {
plsql.parseResource("ExecuteImmediate1047a.pls");
}
@Test
void parseExecuteImmediate1047b() {
plsql.parseResource("ExecuteImmediate1047b.pls");
}
@Test
void parseExecuteImmediateString() {
plsql.parseResource("ExecuteImmediateString.pls");
}
}
| 642 | 21.964286 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/SelectForUpdateTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class SelectForUpdateTest extends AbstractPLSQLParserTst {
@Test
void parseSelectForUpdateWait() {
ASTInput input = plsql.parseResource("SelectForUpdateWait.pls");
assertNotNull(input);
assertEquals(5, input.findDescendantsOfType(ASTForUpdateClause.class).size());
}
@Test
void parseSelectForUpdate() {
ASTInput input = plsql.parseResource("SelectForUpdate.pls");
assertNotNull(input);
List<ASTForUpdateClause> forUpdateClauses = input.findDescendantsOfType(ASTForUpdateClause.class);
assertEquals(2, forUpdateClauses.size());
assertEquals(2, forUpdateClauses.get(1).getNumChildren());
assertEquals("e", forUpdateClauses.get(1).getChild(0).getImage());
assertEquals("salary", forUpdateClauses.get(1).getChild(1).getImage());
}
}
| 1,216 | 32.805556 | 106 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/InsertIntoClauseTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class InsertIntoClauseTest extends AbstractPLSQLParserTst {
@Test
void parseInsertInto() {
plsql.parseResource("InsertIntoClause.pls");
}
@Test
void parseInsertIntoReturning() {
plsql.parseResource("InsertIntoClauseReturning.pls");
}
@Test
void parseInsertIntoWithRecord() {
plsql.parseResource("InsertIntoClauseRecord.pls");
}
}
| 626 | 21.392857 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/InOutNoCopyTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
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.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class InOutNoCopyTest extends AbstractPLSQLParserTst {
@Test
void parseInOutNoCopy() {
ASTInput input = plsql.parseResource("InOutNoCopy.pls");
assertNotNull(input);
List<ASTFormalParameter> params = input.findDescendantsOfType(ASTFormalParameter.class);
assertEquals(18, params.size());
//detailed check of first 6 test cases
assertFalse(params.get(0).isIn());
assertFalse(params.get(0).isOut());
assertFalse(params.get(0).isNoCopy());
assertTrue(params.get(1).isIn());
assertFalse(params.get(1).isOut());
assertFalse(params.get(1).isNoCopy());
assertFalse(params.get(2).isIn());
assertTrue(params.get(2).isOut());
assertFalse(params.get(2).isNoCopy());
assertTrue(params.get(3).isIn());
assertTrue(params.get(3).isOut());
assertFalse(params.get(3).isNoCopy());
assertTrue(params.get(4).isIn());
assertTrue(params.get(4).isOut());
assertTrue(params.get(4).isNoCopy());
assertFalse(params.get(5).isIn());
assertTrue(params.get(5).isOut());
assertTrue(params.get(5).isNoCopy());
//piecemeal test of other test cases
assertFalse(params.get(11).isIn());
assertTrue(params.get(11).isOut());
assertTrue(params.get(11).isNoCopy());
assertTrue(params.get(16).isIn());
assertTrue(params.get(16).isOut());
assertTrue(params.get(16).isNoCopy());
}
}
| 1,994 | 35.272727 | 96 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTComparisonConditionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst;
class ASTComparisonConditionTest extends AbstractPLSQLParserTst {
@Test
void testOperator() {
ASTInput input = plsql.parse("BEGIN SELECT COUNT(1) INTO MY_TABLE FROM USERS_TABLE WHERE user_id = 1; END;");
List<ASTComparisonCondition> conditions = input.findDescendantsOfType(ASTComparisonCondition.class);
assertEquals(1, conditions.size());
assertEquals("=", conditions.get(0).getOperator());
}
}
| 761 | 29.48 | 117 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/errorprone/ToDateWithoutDateFormatTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.errorprone;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ToDateWithoutDateFormatTest extends PmdRuleTst {
// No additional unit tests
@Override
protected List<Rule> getRules() {
Rule rule = findRule("category/plsql/errorprone.xml", "TO_DATEWithoutDateFormat");
return Collections.singletonList(rule);
}
}
| 574 | 25.136364 | 90 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/errorprone/ToDateToCharTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.errorprone;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ToDateToCharTest extends PmdRuleTst {
// No additional unit tests
@Override
protected List<Rule> getRules() {
Rule rule = findRule("category/plsql/errorprone.xml", "TO_DATE_TO_CHAR");
return Collections.singletonList(rule);
}
}
| 554 | 24.227273 | 81 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/errorprone/ToTimestampWithoutDateFormatTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.errorprone;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ToTimestampWithoutDateFormatTest extends PmdRuleTst {
// No additional unit tests
@Override
protected List<Rule> getRules() {
Rule rule = findRule("category/plsql/errorprone.xml", "TO_TIMESTAMPWithoutDateFormat");
return Collections.singletonList(rule);
}
}
| 584 | 25.590909 | 95 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/bestpractices/TomKytesDespairTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class TomKytesDespairTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/AvoidTabCharacterTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class AvoidTabCharacterTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/LineLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class LineLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/MisplacedPragmaTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class MisplacedPragmaTest extends PmdRuleTst {
// no additional unit tests
}
| 280 | 22.416667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/ForLoopNamingTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ForLoopNamingTest extends PmdRuleTst {
// no additional unit tests
}
| 278 | 22.25 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/CodeFormatTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CodeFormatTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.