Migrate leftover tests to JUnit5

This commit is contained in:
Andreas Dangel 2022-10-03 16:15:30 +02:00
parent 9cbdd4b588
commit 8688838190
No known key found for this signature in database
GPG Key ID: 93450DF2DF9A3FA3
32 changed files with 425 additions and 438 deletions

View File

@ -4,11 +4,11 @@
package net.sourceforge.pmd.lang.apex.ast;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ApexCommentTest extends ApexParserTestBase {
import org.junit.jupiter.api.Test;
class ApexCommentTest extends ApexParserTestBase {
@Test
public void testContainsComment1() {
@ -18,6 +18,6 @@ public class ApexCommentTest extends ApexParserTestBase {
+ "}}}");
ASTCatchBlockStatement catchBlock = file.descendants(ASTCatchBlockStatement.class).crossFindBoundaries().firstOrThrow();
Assert.assertTrue(catchBlock.getContainsComment());
assertTrue(catchBlock.getContainsComment());
}
}

View File

@ -23,7 +23,7 @@ import net.sourceforge.pmd.util.IOUtil;
import com.github.stefanbirkner.systemlambda.SystemLambda;
public class ApexMultifileAnalysisTest {
class ApexMultifileAnalysisTest {
@TempDir
private Path tempFolder;

View File

@ -8,7 +8,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
@ -83,7 +83,7 @@ public class PmdAnalysisTest {
}
@Test
public void testParseException() {
void testParseException() {
PMDConfiguration config = new PMDConfiguration();
config.setThreads(1);
config.setForceLanguageVersion(PmdRunnableTest.getVersionWithParserThatThrowsSemanticError());
@ -92,13 +92,13 @@ public class PmdAnalysisTest {
pmd.files().addSourceFile("file", "some source");
ReportStats stats = pmd.runAndReturnStats();
assertEquals("Errors", 1, stats.getNumErrors());
assertEquals("Violations", 0, stats.getNumViolations());
assertEquals(1, stats.getNumErrors(), "Errors");
assertEquals(0, stats.getNumViolations(), "Violations");
}
}
@Test
public void testFileWithSpecificLanguage() {
void testFileWithSpecificLanguage() {
final Language language = Dummy2LanguageModule.getInstance();
PMDConfiguration config = new PMDConfiguration();
config.setIgnoreIncrementalAnalysis(true);
@ -117,7 +117,7 @@ public class PmdAnalysisTest {
}
@Test
public void testTextFileWithSpecificLanguage() {
void testTextFileWithSpecificLanguage() {
final Language language = Dummy2LanguageModule.getInstance();
PMDConfiguration config = new PMDConfiguration();
config.setIgnoreIncrementalAnalysis(true);

View File

@ -5,7 +5,7 @@
package net.sourceforge.pmd;
import static net.sourceforge.pmd.util.CollectionUtil.buildMap;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.eq;
@ -32,12 +32,12 @@ import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
public class RulesetFactoryTestBase {
class RulesetFactoryTestBase {
protected MessageReporter mockReporter;
@BeforeEach
public void setup() {
void setup() {
SimpleMessageReporter reporter = new SimpleMessageReporter(LoggerFactory.getLogger(RulesetFactoryTestBase.class));
mockReporter = spy(reporter);
}

View File

@ -4,26 +4,26 @@
package net.sourceforge.pmd.lang.ast.impl.javacc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.EOFException;
import java.io.IOException;
import java.util.Collections;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.document.TextDocument;
public class CharStreamTest {
class CharStreamTest {
private LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
@Test
public void testReadZeroChars() throws IOException {
void testReadZeroChars() throws IOException {
CharStream stream = simpleCharStream("");
@ -34,7 +34,7 @@ public class CharStreamTest {
}
@Test
public void testMultipleEofReads() throws IOException {
void testMultipleEofReads() throws IOException {
CharStream stream = simpleCharStream("");
@ -45,7 +45,7 @@ public class CharStreamTest {
}
@Test
public void testReadStuff() throws IOException {
void testReadStuff() throws IOException {
CharStream stream = simpleCharStream("abcd");
@ -58,7 +58,7 @@ public class CharStreamTest {
}
@Test
public void testReadBacktrack() throws IOException {
void testReadBacktrack() throws IOException {
CharStream stream = simpleCharStream("abcd");
@ -78,7 +78,7 @@ public class CharStreamTest {
}
@Test
public void testReadBacktrackWithEscapes() throws IOException {
void testReadBacktrackWithEscapes() throws IOException {
CharStream stream = javaCharStream("__\\u00a0_\\u00a0_");
@ -106,7 +106,7 @@ public class CharStreamTest {
}
@Test
public void testBacktrackTooMuch() throws IOException {
void testBacktrackTooMuch() throws IOException {
CharStream stream = simpleCharStream("abcd");
@ -121,7 +121,7 @@ public class CharStreamTest {
}
@Test
public void testBacktrackTooMuch2() throws IOException {
void testBacktrackTooMuch2() throws IOException {
CharStream stream = simpleCharStream("abcd");
@ -134,11 +134,11 @@ public class CharStreamTest {
}
public CharStream simpleCharStream(String abcd) {
CharStream simpleCharStream(String abcd) {
return CharStream.create(TextDocument.readOnlyString(abcd, dummyVersion), TokenDocumentBehavior.DEFAULT);
}
public CharStream javaCharStream(String abcd) {
CharStream javaCharStream(String abcd) {
return CharStream.create(
TextDocument.readOnlyString(abcd, dummyVersion),
new TokenDocumentBehavior(Collections.emptyList()) {

View File

@ -4,27 +4,27 @@
package net.sourceforge.pmd.lang.ast.impl.javacc;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.document.TextDocument;
public class JavaEscapeReaderTest {
class JavaEscapeReaderTest {
public TextDocument readString(String input) {
TextDocument readString(String input) {
TextDocument intext = TextDocument.readOnlyString(Chars.wrap(input), DummyLanguageModule.getInstance().getDefaultVersion());
return new JavaEscapeTranslator(intext).translateDocument();
}
@Test
public void testSimpleRead() throws IOException {
void testSimpleRead() throws IOException {
String input = "abcdede";
try (TextDocument r = readString(input)) {
@ -33,7 +33,7 @@ public class JavaEscapeReaderTest {
}
@Test
public void testNotAnEscape1Read() throws IOException {
void testNotAnEscape1Read() throws IOException {
String input = "abc\\dede";
try (TextDocument r = readString(input)) {
@ -42,7 +42,7 @@ public class JavaEscapeReaderTest {
}
@Test
public void testNotAnEscape1Read2() throws IOException {
void testNotAnEscape1Read2() throws IOException {
String input = "abc\\\\\\dede";
try (TextDocument r = readString(input)) {
@ -51,7 +51,7 @@ public class JavaEscapeReaderTest {
}
@Test
public void testAnEscapeStopAtEnd() throws IOException {
void testAnEscapeStopAtEnd() throws IOException {
String input = "abc\\\\\\u00a0dede";
try (TextDocument r = readString(input)) {
@ -60,7 +60,7 @@ public class JavaEscapeReaderTest {
}
@Test
public void testSeveralEscapes() throws IOException {
void testSeveralEscapes() throws IOException {
String input = "abc\\\\\\u00a0d\\uu00a0ede";
try (TextDocument r = readString(input)) {
@ -69,7 +69,7 @@ public class JavaEscapeReaderTest {
}
@Test
public void testAnEscapeInsideBlock() throws IOException {
void testAnEscapeInsideBlock() throws IOException {
String input = "abc\\\\\\u00a0dede\\u00a0";
try (TextDocument r = readString(input)) {

View File

@ -26,22 +26,22 @@ import net.sourceforge.pmd.util.CollectionUtil;
/**
*
*/
public class CharsTest {
class CharsTest {
@Test
public void wrapStringRoundTrip() {
void wrapStringRoundTrip() {
String s = "ooo";
assertSame(s, Chars.wrap(s).toString());
}
@Test
public void wrapCharsRoundTrip() {
void wrapCharsRoundTrip() {
Chars s = Chars.wrap("ooo");
assertSame(s, Chars.wrap(s));
}
@Test
public void appendChars() {
void appendChars() {
StringBuilder sb = new StringBuilder();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
@ -51,7 +51,7 @@ public class CharsTest {
}
@Test
public void appendCharsWithOffsets() {
void appendCharsWithOffsets() {
StringBuilder sb = new StringBuilder();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
@ -61,7 +61,7 @@ public class CharsTest {
}
@Test
public void toStringBuilder() {
void toStringBuilder() {
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
@ -69,7 +69,7 @@ public class CharsTest {
}
@Test
public void write() throws IOException {
void write() throws IOException {
StringWriter writer = new StringWriter();
Chars bc = Chars.wrap("abcd").slice(1, 2);
assertEquals("bc", bc.toString());
@ -82,7 +82,7 @@ public class CharsTest {
}
@Test
public void getChars() {
void getChars() {
char[] arr = new char[4];
Chars bc = Chars.wrap("abcd").slice(1, 2);
@ -97,7 +97,7 @@ public class CharsTest {
}
@Test
public void indexOf() {
void indexOf() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.indexOf('b', 0));
@ -111,7 +111,7 @@ public class CharsTest {
}
@Test
public void indexOfString() {
void indexOfString() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.indexOf("b", 0));
@ -136,7 +136,7 @@ public class CharsTest {
}
@Test
public void lastIndexOf() {
void lastIndexOf() {
Chars bc = Chars.wrap("aaaaabcdb").slice(5, 2);
// --
assertEquals(0, bc.lastIndexOf('b', 0));
@ -153,7 +153,7 @@ public class CharsTest {
}
@Test
public void startsWith() {
void startsWith() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
assertTrue(bc.startsWith("bc"));
@ -179,7 +179,7 @@ public class CharsTest {
}
@Test
public void removeSuffix() {
void removeSuffix() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
// --
@ -195,7 +195,7 @@ public class CharsTest {
}
@Test
public void removePrefix() {
void removePrefix() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
// --
@ -213,7 +213,7 @@ public class CharsTest {
}
@Test
public void trimNoop() {
void trimNoop() {
Chars bc = Chars.wrap("abcdb").slice(1, 2);
assertEquals("bc", bc.toString());
assertEquals("bc", bc.trimStart().toString());
@ -222,7 +222,7 @@ public class CharsTest {
}
@Test
public void trimStartAndEnd() {
void trimStartAndEnd() {
Chars bc = Chars.wrap("a bc db").slice(1, 6);
// ------
assertEquals(" bc ", bc.toString());
@ -232,7 +232,7 @@ public class CharsTest {
}
@Test
public void charAt() {
void charAt() {
Chars bc = Chars.wrap("a bc db").slice(1, 6);
// ------
@ -245,7 +245,7 @@ public class CharsTest {
}
@Test
public void linesTest() {
void linesTest() {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
@ -254,28 +254,28 @@ public class CharsTest {
}
@Test
public void linesTest2() {
void linesTest2() {
Chars bc = Chars.wrap("aa\n");
List<String> lines = CollectionUtil.map(bc.lines(), Chars::toString);
assertEquals(listOf("aa"), lines);
}
@Test
public void linesStreamTest() {
void linesStreamTest() {
Chars bc = Chars.wrap("aa\nb\rded\r\nlff");
List<String> lines = bc.lineStream().map(Chars::toString).collect(Collectors.toList());
assertEquals(listOf("aa", "b", "ded", "lff"), lines);
}
@Test
public void linesTest3WithCr() {
void linesTest3WithCr() {
Chars bc = Chars.wrap("aa\rb");
List<String> lines = CollectionUtil.map(bc.lines(), Chars::toString);
assertEquals(listOf("aa", "b"), lines);
}
@Test
public void testEqualsHashCode() {
void testEqualsHashCode() {
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
@ -292,7 +292,7 @@ public class CharsTest {
}
@Test
public void testContentEquals() {
void testContentEquals() {
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
@ -308,7 +308,7 @@ public class CharsTest {
}
@Test
public void testSlice() {
void testSlice() {
// slice is offset + length
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
@ -318,7 +318,7 @@ public class CharsTest {
}
@Test
public void testSubsequence() {
void testSubsequence() {
// subsequence is start + end
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
@ -328,7 +328,7 @@ public class CharsTest {
}
@Test
public void testSubstring() {
void testSubstring() {
// substring is start + end
Chars chars = Chars.wrap("a_a_b_c_s").slice(2, 5);
// -----
@ -339,7 +339,7 @@ public class CharsTest {
@Test
public void testTrimBlankLines() {
void testTrimBlankLines() {
assertTrimBlankLinesEquals(" \n \n abc \n \n de \n \n ",
" abc \n \n de ");
assertTrimBlankLinesEquals("", "");
@ -352,7 +352,7 @@ public class CharsTest {
@Test
public void testReaderSingleChars() throws IOException {
void testReaderSingleChars() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
@ -371,7 +371,7 @@ public class CharsTest {
}
@Test
public void testReaderBuffer() throws IOException {
void testReaderBuffer() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
@ -389,7 +389,7 @@ public class CharsTest {
}
@Test
public void testReaderSlicedBuffer() throws IOException {
void testReaderSlicedBuffer() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
@ -408,7 +408,7 @@ public class CharsTest {
}
@Test
public void testReadClosed() throws IOException {
void testReadClosed() throws IOException {
Chars bc = Chars.wrap("a \n \r\nbc db").slice(1, 9);
// ------------
@ -418,7 +418,7 @@ public class CharsTest {
}
@Test
public void testReaderMark() throws IOException {
void testReaderMark() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
@ -448,7 +448,7 @@ public class CharsTest {
}
@Test
public void testReaderMissingMark() throws IOException {
void testReaderMissingMark() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
@ -461,7 +461,7 @@ public class CharsTest {
}
@Test
public void testReaderSkip() throws IOException {
void testReaderSkip() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
@ -485,7 +485,7 @@ public class CharsTest {
}
@Test
public void testReaderInvalidParams() throws IOException {
void testReaderInvalidParams() throws IOException {
Chars bc = Chars.wrap("abcdefghijklmnop").slice(1, 9);
// ------------
char[] cbuf = new char[4];

View File

@ -5,18 +5,18 @@
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
public class FileLocationTest {
class FileLocationTest {
@Test
public void testSimple() {
void testSimple() {
FileLocation loc = FileLocation.range("fname", TextRange2d.range2d(1, 1, 1, 2));
assertEquals("fname", loc.getFileName());
assertEquals(1, loc.getStartLine());
@ -26,14 +26,14 @@ public class FileLocationTest {
}
@Test
public void testToRange() {
void testToRange() {
TextRange2d range2d = TextRange2d.range2d(1, 1, 1, 2);
FileLocation loc = FileLocation.range("fname", range2d);
assertEquals(range2d, loc.toRange2d());
}
@Test
public void testToString() {
void testToString() {
FileLocation loc = FileLocation.range("fname", TextRange2d.range2d(1, 1, 1, 2));
assertEquals(
@ -45,7 +45,7 @@ public class FileLocationTest {
loc.startPosToStringWithFile()
);
MatcherAssert.assertThat(loc.toString(), containsString("!debug only!"));
assertThat(loc.toString(), containsString("!debug only!"));
}
}

View File

@ -12,10 +12,10 @@ import org.junit.jupiter.api.Test;
/**
* Unit test for {@link SourceCodePositioner}.
*/
public class SourceCodePositionerTest {
class SourceCodePositionerTest {
@Test
public void testLineNumberFromOffset() {
void testLineNumberFromOffset() {
final String source = "abcd\ndefghi\n\rjklmn\ropq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
@ -48,7 +48,7 @@ public class SourceCodePositionerTest {
}
@Test
public void testOffsetFromLineColumn() {
void testOffsetFromLineColumn() {
final String source = "abcd\ndefghi\r\njklmn\nopq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
@ -71,7 +71,7 @@ public class SourceCodePositionerTest {
@Test
public void testWrongOffsets() {
void testWrongOffsets() {
final String source = "abcd\ndefghi\r\njklmn\nopq";
SourceCodePositioner positioner = SourceCodePositioner.create(source);
@ -89,7 +89,7 @@ public class SourceCodePositionerTest {
@Test
public void testEmptyDocument() {
void testEmptyDocument() {
SourceCodePositioner positioner = SourceCodePositioner.create("");
@ -105,7 +105,7 @@ public class SourceCodePositionerTest {
}
@Test
public void testDocumentStartingWithNl() {
void testDocumentStartingWithNl() {
SourceCodePositioner positioner = SourceCodePositioner.create("\n");
@ -121,7 +121,7 @@ public class SourceCodePositionerTest {
@Test
public void lineToOffsetMappingWithLineFeedShouldSucceed() {
void lineToOffsetMappingWithLineFeedShouldSucceed() {
final String code = "public static int main(String[] args) {\n"
+ "int var;\n"
+ "}";
@ -132,7 +132,7 @@ public class SourceCodePositionerTest {
}
@Test
public void lineToOffsetMappingWithCarriageReturnFeedLineFeedShouldSucceed() {
void lineToOffsetMappingWithCarriageReturnFeedLineFeedShouldSucceed() {
final String code = "public static int main(String[] args) {\r\n"
+ "int var;\r\n"
+ "}";
@ -143,7 +143,7 @@ public class SourceCodePositionerTest {
}
@Test
public void lineToOffsetMappingWithMixedLineSeparatorsShouldSucceed() {
void lineToOffsetMappingWithMixedLineSeparatorsShouldSucceed() {
final String code = "public static int main(String[] args) {\r\n"
+ "int var;\n"
+ "}";

View File

@ -6,26 +6,23 @@ package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyVersion;
import static net.sourceforge.pmd.lang.document.TextPos2d.pos2d;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageVersion;
import net.sourceforge.pmd.util.IOUtil;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
public class TextDocumentTest {
class TextDocumentTest {
@Test
public void testSingleLineRegion() {
void testSingleLineRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, "bonjour".length());
@ -44,7 +41,7 @@ public class TextDocumentTest {
}
@Test
public void testRegionAtEol() {
void testRegionAtEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, "bonjour\n".length());
@ -59,7 +56,7 @@ public class TextDocumentTest {
}
@Test
public void testEmptyRegionAtEol() {
void testEmptyRegionAtEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
// ^ The caret position right after the \n
// We consider it's part of the next line
@ -76,7 +73,7 @@ public class TextDocumentTest {
}
@Test
public void testRegionForEol() {
void testRegionForEol() {
TextDocument doc = TextDocument.readOnlyString("bonjour\ntristesse", dummyVersion());
// [ [ The region containing the \n
// We consider it ends on the same line, not the next one
@ -94,7 +91,7 @@ public class TextDocumentTest {
}
@Test
public void testRegionAtEndOfFile() {
void testRegionAtEndOfFile() {
TextDocument doc = TextDocument.readOnlyString("flemme", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength(0, doc.getLength());
@ -109,7 +106,7 @@ public class TextDocumentTest {
}
@Test
public void testMultiLineRegion() {
void testMultiLineRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength("bonjou".length(), "r\noha\ntri".length());
@ -128,7 +125,7 @@ public class TextDocumentTest {
@Test
public void testLineColumnFromOffset() {
void testLineColumnFromOffset() {
TextDocument doc = TextDocument.readOnlyString("ab\ncd\n", dummyVersion());
assertPos2dEqualsAt(doc, 0, "a", pos2d(1, 1), true);
@ -151,7 +148,7 @@ public class TextDocumentTest {
}
@Test
public void testEmptyRegion() {
void testEmptyRegion() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
TextRegion region = TextRegion.fromOffsetLength("bonjour".length(), 0);
@ -170,7 +167,7 @@ public class TextDocumentTest {
@Test
public void testLineRange() {
void testLineRange() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
assertEquals(Chars.wrap("bonjour\n"), doc.sliceTranslatedText(doc.createLineRange(1, 1)));
@ -182,46 +179,40 @@ public class TextDocumentTest {
assertThrows(IndexOutOfBoundsException.class, () -> doc.createLineRange(0, 2));
}
@Test
@Parameters(source = DocumentsProvider.class)
public void testEntireRegion(TextDocument doc) {
assertEquals("getEntireRegion should return something based on length",
TextRegion.fromOffsetLength(0, doc.getLength()),
doc.getEntireRegion());
@ParameterizedTest
@MethodSource("documentProvider")
void testEntireRegion(TextDocument doc) {
assertEquals(TextRegion.fromOffsetLength(0, doc.getLength()),
doc.getEntireRegion(),
"getEntireRegion should return something based on length");
}
@Test
@Parameters(source = DocumentsProvider.class)
public void testReader(TextDocument doc) throws IOException {
@ParameterizedTest
@MethodSource("documentProvider")
void testReader(TextDocument doc) throws IOException {
assertEquals("NewReader should read the text",
doc.getText().toString(),
IOUtil.readToString(doc.newReader())
);
assertEquals(doc.getText().toString(),
IOUtil.readToString(doc.newReader()),
"NewReader should read the text");
}
@Test
public void testRegionOutOfBounds() {
void testRegionOutOfBounds() {
TextDocument doc = TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion());
assertThrows(AssertionError.class, () -> TextRegion.isValidRegion(0, 40, doc));
}
// for junit params runner
public static final class DocumentsProvider {
@SuppressWarnings("resource")
public static Object[] provideParameters() {
LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
return new TextDocument[] {
TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion),
TextDocument.readOnlyString("bonjour\n", dummyVersion),
TextDocument.readOnlyString("\n", dummyVersion),
TextDocument.readOnlyString("", dummyVersion),
};
}
@SuppressWarnings("resource")
static Object[] documentProvider() {
LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion();
return new TextDocument[] {
TextDocument.readOnlyString("bonjour\noha\ntristesse", dummyVersion),
TextDocument.readOnlyString("bonjour\n", dummyVersion),
TextDocument.readOnlyString("\n", dummyVersion),
TextDocument.readOnlyString("", dummyVersion),
};
}
}

View File

@ -4,137 +4,132 @@
package net.sourceforge.pmd.lang.document;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
public class TextFileContentTest {
class TextFileContentTest {
// in real life it's System.lineSeparator()
// to make the class more testable (and avoid some test failures being hidden depending on the platform),
// we use this dummy value
private static final String LINESEP_SENTINEL = ":fallback:";
@Rule
public ExpectedException expect = ExpectedException.none();
@Test
@Parameters(source = TextContentOrigin.class)
public void testMixedDelimiters(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testMixedDelimiters(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\r\nb\n\rc");
Assert.assertEquals(Chars.wrap("a\nb\n\nc"), content.getNormalizedText());
Assert.assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
assertEquals(Chars.wrap("a\nb\n\nc"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testFormFeedIsNotNewline(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testFormFeedIsNotNewline(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\f\nb\nc");
Assert.assertEquals(Chars.wrap("a\f\nb\nc"), content.getNormalizedText());
Assert.assertEquals("\n", content.getLineTerminator());
assertEquals(Chars.wrap("a\f\nb\nc"), content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@Test
public void testNormTextPreservation() {
void testNormTextPreservation() {
Chars input = Chars.wrap("a\nb\nc");
TextFileContent content = TextFileContent.fromCharSeq(input);
Assert.assertSame(input, content.getNormalizedText());
Assert.assertEquals("\n", content.getLineTerminator());
assertSame(input, content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testBomElimination(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testBomElimination(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("\ufeffabc");
Chars normalizedText = content.getNormalizedText();
Assert.assertEquals(Chars.wrap("abc"), normalizedText);
assertEquals(Chars.wrap("abc"), normalizedText);
// This means the string underlying the Chars does not start with the bom marker.
// It's useful for performance to have `textDocument.getText().toString()` be O(1),
// and not create a new string.
Assert.assertTrue("should be full string", normalizedText.isFullString());
Assert.assertSame(normalizedText.toString(), normalizedText.toString());
assertTrue(normalizedText.isFullString(), "should be full string");
assertSame(normalizedText.toString(), normalizedText.toString());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testNoExplicitLineMarkers(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testNoExplicitLineMarkers(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a");
Assert.assertEquals(Chars.wrap("a"), content.getNormalizedText());
Assert.assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
assertEquals(Chars.wrap("a"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testEmptyFile(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testEmptyFile(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("");
Assert.assertEquals(Chars.wrap(""), content.getNormalizedText());
Assert.assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
assertEquals(Chars.wrap(""), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@Test
public void testCrlfSplitOnBuffer() throws IOException {
void testCrlfSplitOnBuffer() throws IOException {
StringReader reader = new StringReader("a\r\nb");
// now the buffer is of size 2, so we read first [a\r] then [\nb]
// but there is a single line
TextFileContent content = TextFileContent.normalizingRead(reader, 2, System.lineSeparator());
Assert.assertEquals(Chars.wrap("a\nb"), content.getNormalizedText());
Assert.assertEquals("\r\n", content.getLineTerminator());
assertEquals(Chars.wrap("a\nb"), content.getNormalizedText());
assertEquals("\r\n", content.getLineTerminator());
}
@Test
public void testCrSplitOnBufferFp() throws IOException {
void testCrSplitOnBufferFp() throws IOException {
StringReader reader = new StringReader("a\rb\n");
// the buffer is of size 2, so we read first [a\r] then [b\n]
// the \r is a line terminator on its own
TextFileContent content = TextFileContent.normalizingRead(reader, 2, LINESEP_SENTINEL);
Assert.assertEquals(Chars.wrap("a\nb\n"), content.getNormalizedText());
Assert.assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
assertEquals(Chars.wrap("a\nb\n"), content.getNormalizedText());
assertEquals(LINESEP_SENTINEL, content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testCrCr(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testCrCr(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\r\rb");
Assert.assertEquals(Chars.wrap("a\n\nb"), content.getNormalizedText());
Assert.assertEquals("\r", content.getLineTerminator());
assertEquals(Chars.wrap("a\n\nb"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testCrIsEol(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testCrIsEol(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("a\rb\rdede");
Assert.assertEquals(Chars.wrap("a\nb\ndede"), content.getNormalizedText());
Assert.assertEquals("\r", content.getLineTerminator());
assertEquals(Chars.wrap("a\nb\ndede"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
@Test
@Parameters(source = TextContentOrigin.class)
public void testLfAtStartOfFile(TextContentOrigin origin) throws IOException {
@ParameterizedTest
@EnumSource
void testLfAtStartOfFile(TextContentOrigin origin) throws IOException {
TextFileContent content = origin.normalize("\nohio");
Assert.assertEquals(Chars.wrap("\nohio"), content.getNormalizedText());
Assert.assertEquals("\n", content.getLineTerminator());
assertEquals(Chars.wrap("\nohio"), content.getNormalizedText());
assertEquals("\n", content.getLineTerminator());
}
@Test
public void testCrCrSplitBuffer() throws IOException {
void testCrCrSplitBuffer() throws IOException {
StringReader reader = new StringReader("a\r\r");
// the buffer is of size 2, so we read first [a\r] then [\ro]
// the \r is not a line terminator though
TextFileContent content = TextFileContent.normalizingRead(reader, 2, LINESEP_SENTINEL);
Assert.assertEquals(Chars.wrap("a\n\n"), content.getNormalizedText());
Assert.assertEquals("\r", content.getLineTerminator());
assertEquals(Chars.wrap("a\n\n"), content.getNormalizedText());
assertEquals("\r", content.getLineTerminator());
}
enum TextContentOrigin {
@ -164,10 +159,5 @@ public class TextFileContentTest {
};
abstract TextFileContent normalize(String input) throws IOException;
// for junitParams
public static Object[] provideParameters() {
return values();
}
}
}

View File

@ -5,12 +5,12 @@
package net.sourceforge.pmd.lang.document;
import static net.sourceforge.pmd.PmdCoreTestUtils.dummyVersion;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedWriter;
import java.io.IOException;
@ -20,22 +20,21 @@ import java.nio.file.Files;
import java.nio.file.Path;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.util.datasource.DataSource;
import net.sourceforge.pmd.util.datasource.FileDataSource;
public class TextFilesTest {
class TextFilesTest {
@Rule
public TemporaryFolder tempDir = TemporaryFolder.builder().build();
@TempDir
Path tempDir;
@Test
public void testNioFile() throws IOException {
void testNioFile() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(file.toAbsolutePath().toString(), tf.getPathId());
@ -46,7 +45,7 @@ public class TextFilesTest {
}
@Test
public void testEquals() throws IOException {
void testEquals() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content").toAbsolutePath();
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
@ -71,7 +70,7 @@ public class TextFilesTest {
}
@Test
public void testStringDataSourceCompat() throws IOException {
void testStringDataSourceCompat() throws IOException {
DataSource ds = DataSource.forString("text", "filename.dummy");
PMDConfiguration config = new PMDConfiguration();
try (TextFile tf = TextFile.dataSourceCompat(ds, config)) {
@ -83,7 +82,7 @@ public class TextFilesTest {
}
@Test
public void testFileDataSourceCompat() throws IOException {
void testFileDataSourceCompat() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
DataSource ds = new FileDataSource(file.toFile());
@ -97,7 +96,7 @@ public class TextFilesTest {
}
@Test
public void testFileDataSourceCompatWithEncoding() throws IOException {
void testFileDataSourceCompatWithEncoding() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_16BE, "some content");
DataSource ds = new FileDataSource(file.toFile());
@ -116,11 +115,11 @@ public class TextFilesTest {
}
@Test
public void testNioFileWrite() throws IOException {
void testNioFileWrite() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
assertFalse("readonly", tf.isReadOnly());
assertFalse(tf.isReadOnly(), "readonly");
// write with CRLF
tf.writeContents(
@ -142,11 +141,11 @@ public class TextFilesTest {
}
@Test
public void testNioFileExplicitReadOnly() throws IOException {
void testNioFileExplicitReadOnly() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion())
.asReadOnly().build()) {
assertTrue("readonly", tf.isReadOnly());
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
@ -155,7 +154,7 @@ public class TextFilesTest {
}
@Test
public void testNioFileCanBeReadMultipleTimes() throws IOException {
void testNioFileCanBeReadMultipleTimes() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText());
@ -164,7 +163,7 @@ public class TextFilesTest {
}
@Test
public void testNioFileBuilder() throws IOException {
void testNioFileBuilder() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some content");
try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion())
.withDisplayName("aname")
@ -177,7 +176,7 @@ public class TextFilesTest {
}
@Test
public void testNioFileEscape() throws IOException {
void testNioFileEscape() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) {
assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText());
@ -185,7 +184,7 @@ public class TextFilesTest {
}
@Test
public void testReaderFile() throws IOException {
void testReaderFile() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), "filename", dummyVersion())) {
assertEquals("filename", tf.getPathId());
@ -196,10 +195,10 @@ public class TextFilesTest {
}
@Test
public void testReaderFileIsReadOnly() throws IOException {
void testReaderFileIsReadOnly() throws IOException {
Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent");
try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), "filename", dummyVersion())) {
assertTrue("readonly", tf.isReadOnly());
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
@ -207,7 +206,7 @@ public class TextFilesTest {
}
@Test
public void testStringFileEscape() throws IOException {
void testStringFileEscape() throws IOException {
try (TextFile tf = TextFile.forCharSeq("cont\r\nents", "filename", dummyVersion())) {
assertEquals("filename", tf.getPathId());
assertEquals("filename", tf.getDisplayName());
@ -220,7 +219,7 @@ public class TextFilesTest {
}
@Test
public void testStringFileCanBeReadMultipleTimes() throws IOException {
void testStringFileCanBeReadMultipleTimes() throws IOException {
try (TextFile tf = TextFile.forCharSeq("contents", "filename", dummyVersion())) {
assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText());
assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText());
@ -229,9 +228,9 @@ public class TextFilesTest {
}
@Test
public void testStringFileIsReadonly() throws IOException {
void testStringFileIsReadonly() throws IOException {
try (TextFile tf = TextFile.forCharSeq("contents", "filename", dummyVersion())) {
assertTrue("readonly", tf.isReadOnly());
assertTrue(tf.isReadOnly(), "readonly");
assertThrows(ReadOnlyFileException.class, () -> tf.writeContents(
TextFileContent.fromCharSeq("new content")
));
@ -239,7 +238,7 @@ public class TextFilesTest {
}
private @NonNull Path makeTmpFile(Charset charset, String content) throws IOException {
Path file = tempDir.newFile().toPath();
Path file = Files.createTempFile(tempDir, null, null);
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(content);
}

View File

@ -5,19 +5,19 @@
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
public class TextPos2dTest {
class TextPos2dTest {
@Test
public void testToString() {
void testToString() {
TextPos2d pos = TextPos2d.pos2d(1, 2);
assertEquals(
"line 1, column 2",
@ -31,11 +31,11 @@ public class TextPos2dTest {
"(line=1, column=2)",
pos.toTupleString()
);
MatcherAssert.assertThat(pos.toString(), containsString("!debug only!"));
assertThat(pos.toString(), containsString("!debug only!"));
}
@Test
public void testEquals() {
void testEquals() {
TextPos2d pos = TextPos2d.pos2d(1, 1);
TextPos2d pos2 = TextPos2d.pos2d(1, 2);
assertNotEquals(pos, pos2);
@ -44,7 +44,7 @@ public class TextPos2dTest {
}
@Test
public void testCompareTo() {
void testCompareTo() {
TextPos2d pos = TextPos2d.pos2d(1, 1);
TextPos2d pos2 = TextPos2d.pos2d(1, 2);
TextPos2d pos3 = TextPos2d.pos2d(2, 1);

View File

@ -5,26 +5,26 @@
package net.sourceforge.pmd.lang.document;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* @author Clément Fournier
*/
public class TextRange2dTest {
class TextRange2dTest {
@Test
public void testCtors() {
void testCtors() {
TextRange2d pos = TextRange2d.range2d(1, 2, 3, 4);
TextRange2d pos2 = TextRange2d.range2d(TextPos2d.pos2d(1, 2), TextPos2d.pos2d(3, 4));
assertEquals(pos, pos2);
}
@Test
public void testEquals() {
void testEquals() {
TextRange2d pos = TextRange2d.range2d(1, 1, 1, 1);
TextRange2d pos2 = TextRange2d.range2d(1, 1, 1, 2);
assertNotEquals(pos, pos2);
@ -33,7 +33,7 @@ public class TextRange2dTest {
}
@Test
public void testCompareTo() {
void testCompareTo() {
TextRange2d pos = TextRange2d.range2d(1, 1, 1, 1);
TextRange2d pos2 = TextRange2d.range2d(1, 1, 1, 2);
@ -43,13 +43,13 @@ public class TextRange2dTest {
}
@Test
public void testToString() {
void testToString() {
TextRange2d range = TextRange2d.range2d(1, 2, 3, 4);
assertEquals(
"1:2-3:4",
range.toDisplayStringWithColon()
);
MatcherAssert.assertThat(range.toString(), containsString("!debug only!"));
assertThat(range.toString(), containsString("!debug only!"));
}
}

View File

@ -4,37 +4,33 @@
package net.sourceforge.pmd.lang.document;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.jupiter.api.Test;
public class TextRegionTest {
@Rule
public ExpectedException expect = ExpectedException.none();
class TextRegionTest {
@Test
public void testIsEmpty() {
void testIsEmpty() {
TextRegion r = TextRegion.fromOffsetLength(0, 0);
assertTrue(r.isEmpty());
}
@Test
public void testEmptyContains() {
void testEmptyContains() {
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
assertFalse(r1.contains(0));
}
@Test
public void testContains() {
void testContains() {
TextRegion r1 = TextRegion.fromOffsetLength(1, 2);
assertFalse(r1.contains(0));
@ -44,7 +40,7 @@ public class TextRegionTest {
}
@Test
public void testIntersectZeroLen() {
void testIntersectZeroLen() {
// r1: [[-----
// r2: [ -----[
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
@ -56,7 +52,7 @@ public class TextRegionTest {
}
@Test
public void testIntersectZeroLen2() {
void testIntersectZeroLen2() {
// r1: -----[[
// r2: [-----[
TextRegion r1 = TextRegion.fromOffsetLength(5, 0);
@ -68,7 +64,7 @@ public class TextRegionTest {
}
@Test
public void testIntersectZeroLen3() {
void testIntersectZeroLen3() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(3, 3);
@ -82,7 +78,7 @@ public class TextRegionTest {
@Test
public void testIntersectZeroLen4() {
void testIntersectZeroLen4() {
TextRegion r1 = TextRegion.fromOffsetLength(0, 0);
TextRegion inter = doIntersect(r1, r1);
@ -91,7 +87,7 @@ public class TextRegionTest {
}
@Test
public void testNonEmptyIntersect() {
void testNonEmptyIntersect() {
// r1: ---[-- --[
// r2: [--- --[--
// i: ---[--[--
@ -104,7 +100,7 @@ public class TextRegionTest {
}
@Test
public void testIntersectContained() {
void testIntersectContained() {
// r1: --[- - ---[
// r2: -- -[-[---
// i: -- -[-[---
@ -117,7 +113,7 @@ public class TextRegionTest {
}
@Test
public void testIntersectDisjoint() {
void testIntersectDisjoint() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(4, 3);
@ -127,7 +123,7 @@ public class TextRegionTest {
}
@Test
public void testOverlapContained() {
void testOverlapContained() {
// r1: --[- - ---[
// r2: -- -[-[---
// i: -- -[-[---
@ -138,7 +134,7 @@ public class TextRegionTest {
}
@Test
public void testOverlapDisjoint() {
void testOverlapDisjoint() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(4, 3);
@ -149,7 +145,7 @@ public class TextRegionTest {
@Test
public void testOverlapBoundary() {
void testOverlapBoundary() {
// r1: -- -[---[
// r2: --[-[---
TextRegion r1 = TextRegion.fromOffsetLength(3, 3);
@ -159,7 +155,7 @@ public class TextRegionTest {
}
@Test
public void testCompare() {
void testCompare() {
// r1: --[-[---
// r2: -- -[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -169,7 +165,7 @@ public class TextRegionTest {
}
@Test
public void testCompareSameOffset() {
void testCompareSameOffset() {
// r1: [-[--
// r2: [- --[
TextRegion r1 = TextRegion.fromOffsetLength(0, 1);
@ -180,7 +176,7 @@ public class TextRegionTest {
@Test
public void testUnion() {
void testUnion() {
// r1: --[-[---
// r2: -- -[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -192,7 +188,7 @@ public class TextRegionTest {
}
@Test
public void testUnionDisjoint() {
void testUnionDisjoint() {
// r1: --[-[- ---
// r2: -- ---[---[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -204,7 +200,7 @@ public class TextRegionTest {
}
@Test
public void testGrowLeft() {
void testGrowLeft() {
// r1: --[-[-
// r2: [-- -[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -215,7 +211,7 @@ public class TextRegionTest {
}
@Test
public void testGrowLeftNegative() {
void testGrowLeftNegative() {
// r1: --[- [-
// r2: -- -[[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -226,16 +222,15 @@ public class TextRegionTest {
}
@Test
public void testGrowLeftOutOfBounds() {
void testGrowLeftOutOfBounds() {
// r1: --[-[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
expect.expect(AssertionError.class);
r1.growLeft(4);
assertThrows(AssertionError.class, () -> r1.growLeft(4));
}
@Test
public void testGrowRight() {
void testGrowRight() {
// r1: --[-[-
// r2: --[- -[
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -246,7 +241,7 @@ public class TextRegionTest {
}
@Test
public void testGrowRightNegative() {
void testGrowRightNegative() {
// r1: --[ -[-
// r2: --[[- -
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
@ -257,39 +252,38 @@ public class TextRegionTest {
}
@Test
public void testGrowRightOutOfBounds() {
void testGrowRightOutOfBounds() {
// r1: --[-[-
TextRegion r1 = TextRegion.fromOffsetLength(2, 1);
expect.expect(AssertionError.class);
r1.growRight(-2);
assertThrows(AssertionError.class, () -> r1.growRight(-2));
}
public void assertRegionEquals(TextRegion region, int start, int len) {
assertEquals("Start offset", start, region.getStartOffset());
assertEquals("Length", len, region.getLength());
private static void assertRegionEquals(TextRegion region, int start, int len) {
assertEquals(start, region.getStartOffset(), "Start offset");
assertEquals(len, region.getLength(), "Length");
}
public void assertIsBefore(TextRegion r1, TextRegion r2) {
assertTrue("Region " + r1 + " should be before " + r2, r1.compareTo(r2) < 0);
assertTrue("Region " + r2 + " should be after " + r1, r2.compareTo(r1) > 0);
private static void assertIsBefore(TextRegion r1, TextRegion r2) {
assertTrue(r1.compareTo(r2) < 0, "Region " + r1 + " should be before " + r2);
assertTrue(r2.compareTo(r1) > 0, "Region " + r2 + " should be after " + r1);
}
private void assertNoOverlap(TextRegion r1, TextRegion r2) {
assertFalse("Regions " + r1 + " and " + r2 + " should not overlap", r1.overlaps(r2));
private static void assertNoOverlap(TextRegion r1, TextRegion r2) {
assertFalse(r1.overlaps(r2), "Regions " + r1 + " and " + r2 + " should not overlap");
}
private void assertOverlap(TextRegion r1, TextRegion r2) {
assertTrue("Regions " + r1 + " and " + r2 + " should overlap", r1.overlaps(r2));
private static void assertOverlap(TextRegion r1, TextRegion r2) {
assertTrue(r1.overlaps(r2), "Regions " + r1 + " and " + r2 + " should overlap");
}
private TextRegion doIntersect(TextRegion r1, TextRegion r2) {
TextRegion inter = TextRegion.intersect(r1, r2);
assertNotNull("Intersection of " + r1 + " and " + r2 + " must exist", inter);
assertNotNull(inter, "Intersection of " + r1 + " and " + r2 + " must exist");
TextRegion symmetric = TextRegion.intersect(r2, r1);
assertEquals("Intersection of " + r1 + " and " + r2 + " must be symmetric", inter, symmetric);
assertEquals(inter, symmetric, "Intersection of " + r1 + " and " + r2 + " must be symmetric");
return inter;
}
@ -297,20 +291,20 @@ public class TextRegionTest {
private TextRegion doUnion(TextRegion r1, TextRegion r2) {
TextRegion union = TextRegion.union(r1, r2);
assertTrue("Union of " + r1 + " and " + r2 + " must contain first region", union.contains(r1));
assertTrue("Union of " + r1 + " and " + r2 + " must contain second region", union.contains(r2));
assertTrue(union.contains(r1), "Union of " + r1 + " and " + r2 + " must contain first region");
assertTrue(union.contains(r2), "Union of " + r1 + " and " + r2 + " must contain second region");
TextRegion symmetric = TextRegion.union(r2, r1);
assertEquals("Union of " + r1 + " and " + r2 + " must be symmetric", union, symmetric);
assertEquals(union, symmetric, "Union of " + r1 + " and " + r2 + " must be symmetric");
return union;
}
private void noIntersect(TextRegion r1, TextRegion r2) {
TextRegion inter = TextRegion.intersect(r1, r2);
assertNull("Intersection of " + r1 + " and " + r2 + " must not exist", inter);
assertNull(inter, "Intersection of " + r1 + " and " + r2 + " must not exist");
TextRegion symmetric = TextRegion.intersect(r2, r1);
assertEquals("Intersection of " + r1 + " and " + r2 + " must be symmetric", inter, symmetric);
assertEquals(inter, symmetric, "Intersection of " + r1 + " and " + r2 + " must be symmetric");
}
}

View File

@ -5,22 +5,22 @@
package net.sourceforge.pmd.util;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.document.Chars;
/**
* @author Clément Fournier
*/
public class CollectionUtilTest {
class CollectionUtilTest {
@Test
public void testJoinOn() {
void testJoinOn() {
testJoinOn(listOf("a", "b", "c"), ".",
"a.b.c");
testJoinOn(Collections.emptyList(), ".",

View File

@ -281,6 +281,11 @@
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -5,23 +5,24 @@
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.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.PMDVersion;
public abstract class AbstractBinaryDistributionTest {
abstract class AbstractBinaryDistributionTest {
public static final String PMD_BIN_PREFIX = "pmd-bin-";
protected static File getBinaryDistribution() {
return new File(".", "target/" + PMD_BIN_PREFIX + PMDVersion.VERSION + ".zip");
}
@ClassRule
public static TemporaryFolder folder = new TemporaryFolder();
@TempDir
static Path folder;
/**
* The temporary directory, to which the binary distribution will be extracted.
@ -29,9 +30,13 @@ public abstract class AbstractBinaryDistributionTest {
*/
protected static Path tempDir;
@BeforeClass
public static void setupTempDirectory() throws Exception {
tempDir = folder.newFolder().toPath();
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);
}

View File

@ -7,30 +7,24 @@ package net.sourceforge.pmd.it;
import java.io.File;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(Parameterized.class)
public class AllRulesIT extends AbstractBinaryDistributionTest {
class AllRulesIT extends AbstractBinaryDistributionTest {
@Parameter
public String language;
@Parameters
public static Iterable<String> languagesToTest() {
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");
}
@Test
public void runRuleTests() throws Exception {
@ParameterizedTest
@MethodSource("languagesToTest")
void runRuleTests(String language) throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/" + language + "/").getAbsolutePath();
ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir,
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir,
"src/test/resources/rulesets/all-" + language + ".xml");
assertDefaultExecutionResult(result);
}

View File

@ -15,9 +15,9 @@ import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.util.IOUtil;
@ -28,12 +28,11 @@ import net.sourceforge.pmd.util.IOUtil;
* <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>.
*/
public class AntIT extends AbstractBinaryDistributionTest {
class AntIT extends AbstractBinaryDistributionTest {
@Test
public void runAnt() throws IOException, InterruptedException {
Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
@EnabledOnOs(OS.LINUX)
void runAnt() throws IOException, InterruptedException {
String antBasepath = new File("target/ant").getAbsolutePath();
String pmdHome = tempDir.resolve(PMD_BIN_PREFIX + PMDVersion.VERSION).toAbsolutePath().toString();
File antTestProjectFolder = prepareAntTestProjectFolder();
@ -46,7 +45,7 @@ public class AntIT extends AbstractBinaryDistributionTest {
private File prepareAntTestProjectFolder() throws IOException {
final Path sourceProjectFolder = new File("src/test/resources/ant-it").toPath();
final Path projectFolder = folder.newFolder().toPath();
final Path projectFolder = Files.createTempDirectory(folder, null);
Files.walkFileTree(sourceProjectFolder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

View File

@ -4,8 +4,8 @@
package net.sourceforge.pmd.it;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.IOException;
@ -15,12 +15,12 @@ import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDVersion;
import net.sourceforge.pmd.cli.internal.CliMessages;
public class BinaryDistributionIT extends AbstractBinaryDistributionTest {
class BinaryDistributionIT extends AbstractBinaryDistributionTest {
private static final String SUPPORTED_LANGUAGES_CPD;
private static final String SUPPORTED_LANGUAGES_PMD;
@ -33,7 +33,7 @@ public class BinaryDistributionIT extends AbstractBinaryDistributionTest {
private final String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath();
@Test
public void testFileExistence() {
void testFileExistence() {
assertTrue(getBinaryDistribution().exists());
}
@ -52,7 +52,7 @@ public class BinaryDistributionIT extends AbstractBinaryDistributionTest {
}
@Test
public void testZipFileContent() throws IOException {
void testZipFileContent() throws IOException {
Set<String> expectedFileNames = getExpectedFileNames();
ZipFile zip = new ZipFile(getBinaryDistribution());
@ -71,65 +71,65 @@ public class BinaryDistributionIT extends AbstractBinaryDistributionTest {
}
@Test
public void testPmdJavaQuickstart() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "rulesets/java/quickstart.xml");
void testPmdJavaQuickstart() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "rulesets/java/quickstart.xml");
result.assertExecutionResult(4, "");
}
@Test
public void testPmdXmlFormat() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml", "xml");
void testPmdXmlFormat() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml", "xml");
result.assertExecutionResult(4, "", "JumbledIncrementer.java\">");
result.assertExecutionResult(4, "", "<violation beginline=\"8\" endline=\"10\" begincolumn=\"13\" endcolumn=\"14\" rule=\"JumbledIncrementer\"");
}
@Test
public void testPmdSample() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
void testPmdSample() throws Exception {
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExecutionResult(4, "", "JumbledIncrementer.java:8:");
}
@Test
public void testPmdHelp() throws Exception {
void testPmdHelp() throws Exception {
ExecutionResult result = PMDExecutor.runPMD(tempDir, "-h");
result.assertExecutionResult(0, SUPPORTED_LANGUAGES_PMD);
}
@Test
public void testPmdNoArgs() throws Exception {
void testPmdNoArgs() throws Exception {
ExecutionResult result = PMDExecutor.runPMD(tempDir); // without any argument, display usage help and error
result.assertExecutionResultErrOutput(1, CliMessages.runWithHelpFlagMessage());
}
@Test
public void logging() throws Exception {
void logging() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath();
ExecutionResult result;
result = PMDExecutor.runPMD(tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-r", folder.newFile().toString());
"-r", createTemporaryReportFile().toString());
result.assertExecutionResult(4);
result.assertErrorOutputContains("[main] INFO net.sourceforge.pmd.PMD - Log level is at INFO");
// now with debug
result = PMDExecutor.runPMD(tempDir, "-d", srcDir, "-R", "src/test/resources/rulesets/sample-ruleset.xml",
"-r", folder.newFile().toString(), "--debug");
"-r", createTemporaryReportFile().toString(), "--debug");
result.assertExecutionResult(4);
result.assertErrorOutputContains("[main] INFO net.sourceforge.pmd.PMD - Log level is at TRACE");
}
@Test
public void runPMDWithError() throws Exception {
void runPMDWithError() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/unparsable/").getAbsolutePath();
ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
ExecutionResult result = PMDExecutor.runPMDRules(createTemporaryReportFile(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExecutionResultErrOutput(0, "Run with --debug to see a stack-trace.");
}
@Test
public void runCPD() throws Exception {
void runCPD() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source-cpd/").getAbsolutePath();
ExecutionResult result;

View File

@ -4,11 +4,11 @@
package net.sourceforge.pmd.it;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
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 static org.junit.jupiter.api.Assertions.fail;
import net.sourceforge.pmd.PMD;
@ -100,18 +100,18 @@ public class ExecutionResult {
}
private void assertExecResultImpl(int expectedExitCode, String output, String expectedOutput, String expectedReport) {
assertEquals("Command exited with wrong code.\nComplete result:\n\n" + this, expectedExitCode, exitCode);
assertNotNull("No output found", output);
assertEquals(expectedExitCode, exitCode, "Command exited with wrong code.\nComplete result:\n\n" + this);
assertNotNull(output, "No output found");
if (expectedOutput != null && !expectedOutput.isEmpty()) {
if (!output.contains(expectedOutput)) {
fail("Expected output '" + expectedOutput + "' not present.\nComplete result:\n\n" + this);
}
} else if (expectedOutput != null && expectedOutput.isEmpty()) {
assertTrue("The output should have been empty.\nComplete result:\n\n" + this, output.isEmpty());
assertTrue(output.isEmpty(), "The output should have been empty.\nComplete result:\n\n" + this);
}
if (expectedReport != null && !expectedReport.isEmpty()) {
assertTrue("Expected report '" + expectedReport + "'.\nComplete result:\n\n" + this,
report.contains(expectedReport));
assertTrue(report.contains(expectedReport),
"Expected report '" + expectedReport + "'.\nComplete result:\n\n" + this);
}
}
@ -120,8 +120,8 @@ public class ExecutionResult {
* @param errorMessage the error message to search for
*/
public void assertNoError(String errorMessage) {
assertFalse("Found error message: " + errorMessage + ".\nComplete result:\n\n" + this,
errorOutput.contains(errorMessage));
assertFalse(errorOutput.contains(errorMessage),
"Found error message: " + errorMessage + ".\nComplete result:\n\n" + this);
}
/**
@ -129,12 +129,12 @@ public class ExecutionResult {
* @param errorMessage the error message to search for
*/
public void assertNoErrorInReport(String errorMessage) {
assertFalse("Found error message in report: " + errorMessage + ".\nComplete result:\n\n" + this,
report.contains(errorMessage));
assertFalse(report.contains(errorMessage),
"Found error message in report: " + errorMessage + ".\nComplete result:\n\n" + this);
}
public void assertErrorOutputContains(String message) {
assertTrue("erroroutput didn't contain " + message, errorOutput.contains(message));
assertTrue(errorOutput.contains(message), "erroroutput didn't contain " + message);
}
static class Builder {

View File

@ -4,19 +4,19 @@
package net.sourceforge.pmd.it;
import static org.junit.Assert.assertTrue;
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.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.PMDVersion;
public class SourceDistributionIT {
class SourceDistributionIT {
private static final String BASE_PATH = "pmd-src-" + PMDVersion.VERSION;
private File getSourceDistribution() {
@ -24,12 +24,12 @@ public class SourceDistributionIT {
}
@Test
public void testFileExistence() {
void testFileExistence() {
assertTrue(getSourceDistribution().exists());
}
@Test
public void verifyExclusions() throws Exception {
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");
@ -38,7 +38,7 @@ public class SourceDistributionIT {
List<String> files = ZipFileExtractor.readZipFile(getSourceDistribution().toPath());
for (String file : files) {
Assert.assertFalse("File " + file + " must not be included", exclusions.contains(file));
assertFalse(exclusions.contains(file), "File " + file + " must not be included");
}
}
}

View File

@ -4,7 +4,7 @@
package net.sourceforge.pmd.it;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileOutputStream;

View File

@ -96,6 +96,11 @@
<artifactId>snakeyaml</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -4,17 +4,17 @@
package net.sourceforge.pmd.docs;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class EscapeUtilsTest {
class EscapeUtilsTest {
@Test
public void testEscapeMarkdown() {
void testEscapeMarkdown() {
assertEquals("This is a \\\\backslash", EscapeUtils.escapeMarkdown("This is a \\backslash"));
assertEquals("This \"\\*\" is not a emphasis", EscapeUtils.escapeMarkdown("This \"*\" is not a emphasis"));
assertEquals("This \"\\*\\*\" is not a strong style", EscapeUtils.escapeMarkdown("This \"**\" is not a strong style"));
@ -25,7 +25,7 @@ public class EscapeUtilsTest {
}
@Test
public void testEscapeHtmlWithinMarkdownSingleLine() {
void testEscapeHtmlWithinMarkdownSingleLine() {
assertEquals("a &lt;script&gt; tag outside of `<script>` backticks should be escaped",
EscapeUtils.escapeSingleLine("a <script> tag outside of `<script>` backticks should be escaped"));
assertEquals("a &lt;script&gt; &quot;tag&quot; outside of `<script>` backticks should be escaped &lt;multiple&gt; times `<strong>`.",
@ -45,7 +45,7 @@ public class EscapeUtilsTest {
}
@Test
public void testEscapeHtmlWithinMarkdownBlocks() {
void testEscapeHtmlWithinMarkdownBlocks() {
String text = "paragraph\n\n> quote <script>\n> quote line \"2\"\n>quote line `<script>` 3\n\n"
+ "next paragraph\n\n code <script> \"a < b\"\n code line 2\n\n"
+ "next paragraph\n\n```\ncode <script> \"a < b\"\ncode line 2\n```\n\n"

View File

@ -4,8 +4,8 @@
package net.sourceforge.pmd.docs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -15,29 +15,28 @@ import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.docs.MockedFileWriter.FileEntry;
import net.sourceforge.pmd.util.IOUtil;
public class RuleDocGeneratorTest {
class RuleDocGeneratorTest {
private MockedFileWriter writer = new MockedFileWriter();
private Path root;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@TempDir
public Path folder;
@Before
public void setup() throws IOException {
@BeforeEach
void setup() throws IOException {
writer.reset();
root = folder.newFolder().toPath();
root = Files.createTempDirectory(folder, null);
Files.createDirectories(root.resolve("docs/_data/sidebars"));
List<String> mockedSidebar = Arrays.asList(
"entries:",
@ -56,7 +55,7 @@ public class RuleDocGeneratorTest {
}
@Test
public void testSingleRuleset() throws IOException {
void testSingleRuleset() throws IOException {
RuleDocGenerator generator = new RuleDocGenerator(writer, root);
RuleSetLoader rsl = new RuleSetLoader().includeDeprecatedRuleReferences(true);

View File

@ -5,26 +5,26 @@
package net.sourceforge.pmd.docs;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.util.IOUtil;
public class RuleSetResolverTest {
class RuleSetResolverTest {
private static final List<String> EXCLUDED_RULESETS = listOf(
IOUtil.normalizePath("pmd-test/src/main/resources/rulesets/dummy/basic.xml")
);
@Test
public void resolveAllRulesets() {
void resolveAllRulesets() {
Path basePath = FileSystems.getDefault().getPath(".").resolve("..").toAbsolutePath().normalize();
List<String> additionalRulesets = GenerateRuleDocsCmd.findAdditionalRulesets(basePath);
@ -38,7 +38,7 @@ public class RuleSetResolverTest {
}
@Test
public void testAdditionalRulesetPattern() {
void testAdditionalRulesetPattern() {
String filePath = IOUtil.normalizePath("/home/foo/pmd/pmd-java/src/main/resources/rulesets/java/quickstart.xml");
assertTrue(GenerateRuleDocsCmd.ADDITIONAL_RULESET_PATTERN.matcher(filePath).matches());
}

View File

@ -5,31 +5,32 @@
package net.sourceforge.pmd.docs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.FileSystems;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RuleTagCheckerTest {
class RuleTagCheckerTest {
@Test
public void testAllChecks() throws Exception {
void testAllChecks() throws Exception {
RuleTagChecker checker = new RuleTagChecker(FileSystems.getDefault().getPath("src/test/resources/ruletagchecker"));
List<String> issues = checker.check();
Assert.assertEquals(7, issues.size());
Assert.assertEquals("ruletag-examples.md: 9: Rule tag for \"java/bestpractices/AvoidPrintStackTrace\" is not closed properly",
assertEquals(7, issues.size());
assertEquals("ruletag-examples.md: 9: Rule tag for \"java/bestpractices/AvoidPrintStackTrace\" is not closed properly",
issues.get(0));
Assert.assertEquals("ruletag-examples.md:12: Rule \"java/notexistingcategory/AvoidPrintStackTrace\" is not found",
assertEquals("ruletag-examples.md:12: Rule \"java/notexistingcategory/AvoidPrintStackTrace\" is not found",
issues.get(1));
Assert.assertEquals("ruletag-examples.md:14: Rule \"java/bestpractices/NotExistingRule\" is not found",
assertEquals("ruletag-examples.md:14: Rule \"java/bestpractices/NotExistingRule\" is not found",
issues.get(2));
Assert.assertEquals("ruletag-examples.md:16: Rule tag for \"java/bestpractices/OtherRule has a missing quote",
assertEquals("ruletag-examples.md:16: Rule tag for \"java/bestpractices/OtherRule has a missing quote",
issues.get(3));
Assert.assertEquals("ruletag-examples.md:17: Rule tag for java/bestpractices/OtherRule\" has a missing quote",
assertEquals("ruletag-examples.md:17: Rule tag for java/bestpractices/OtherRule\" has a missing quote",
issues.get(4));
Assert.assertEquals("ruletag-examples.md:21: Rule tag for \"OtherRule has a missing quote", issues.get(5));
Assert.assertEquals("ruletag-examples.md:22: Rule tag for OtherRule\" has a missing quote", issues.get(6));
assertEquals("ruletag-examples.md:21: Rule tag for \"OtherRule has a missing quote", issues.get(5));
assertEquals("ruletag-examples.md:22: Rule tag for OtherRule\" has a missing quote", issues.get(6));
}
}

View File

@ -4,7 +4,7 @@
package net.sourceforge.pmd.docs;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -16,8 +16,8 @@ import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
@ -28,16 +28,16 @@ import net.sourceforge.pmd.lang.Language;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.util.IOUtil;
public class SidebarGeneratorTest {
class SidebarGeneratorTest {
private MockedFileWriter writer = new MockedFileWriter();
@Before
public void setup() {
@BeforeEach
void setup() {
writer.reset();
}
@Test
public void testSidebar() throws IOException {
void testSidebar() throws IOException {
Map<Language, List<RuleSet>> rulesets = new HashMap<>();
RuleSet ruleSet1 = RuleSet.create("test", "test", "bestpractices.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
RuleSet ruleSet2 = RuleSet.create("test2", "test", "codestyle.xml", Collections.emptyList(), Collections.emptyList(), Collections.emptyList());

Some files were not shown because too many files have changed in this diff Show More