Merge branch 'pr-2813' into master

[core] Use JUnit's TemporaryFolder rule #2813
This commit is contained in:
Andreas Dangel
2020-10-10 14:01:03 +02:00
11 changed files with 56 additions and 99 deletions

View File

@ -33,6 +33,7 @@ This is a {{ site.pmd.release_type }} release.
* [#2803](https://github.com/pmd/pmd/pull/2803): \[java] Improve DoNotCallSystemExit (Fixes #2157) - [Vitaly Polonetsky](https://github.com/mvitaly) * [#2803](https://github.com/pmd/pmd/pull/2803): \[java] Improve DoNotCallSystemExit (Fixes #2157) - [Vitaly Polonetsky](https://github.com/mvitaly)
* [#2809](https://github.com/pmd/pmd/pull/2809): \[java] Move test config from file to test class - [Stefan Birkner](https://github.com/stefanbirkner) * [#2809](https://github.com/pmd/pmd/pull/2809): \[java] Move test config from file to test class - [Stefan Birkner](https://github.com/stefanbirkner)
* [#2810](https://github.com/pmd/pmd/pull/2810): \[core] Move method "renderTempFile" to XMLRendererTest - [Stefan Birkner](https://github.com/stefanbirkner) * [#2810](https://github.com/pmd/pmd/pull/2810): \[core] Move method "renderTempFile" to XMLRendererTest - [Stefan Birkner](https://github.com/stefanbirkner)
* [#2813](https://github.com/pmd/pmd/pull/2813): \[core] Use JUnit's TemporaryFolder rule - [Stefan Birkner](https://github.com/stefanbirkner)
{% endtocmaker %} {% endtocmaker %}

View File

@ -19,7 +19,9 @@ import java.nio.charset.StandardCharsets;
import java.util.Properties; import java.util.Properties;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import net.sourceforge.pmd.cache.FileAnalysisCache; import net.sourceforge.pmd.cache.FileAnalysisCache;
import net.sourceforge.pmd.cache.NoopAnalysisCache; import net.sourceforge.pmd.cache.NoopAnalysisCache;
@ -29,6 +31,9 @@ import net.sourceforge.pmd.util.ClasspathClassLoader;
public class ConfigurationTest { public class ConfigurationTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test @Test
public void testSuppressMarker() { public void testSuppressMarker() {
PMDConfiguration configuration = new PMDConfiguration(); PMDConfiguration configuration = new PMDConfiguration();
@ -227,8 +232,7 @@ public class ConfigurationTest {
configuration.setAnalysisCache(null); configuration.setAnalysisCache(null);
assertNotNull("Default cache was set to null", configuration.getAnalysisCache()); assertNotNull("Default cache was set to null", configuration.getAnalysisCache());
final File cacheFile = File.createTempFile("pmd-", ".cache"); final File cacheFile = folder.newFile();
cacheFile.deleteOnExit();
final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile); final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile);
configuration.setAnalysisCache(analysisCache); configuration.setAnalysisCache(analysisCache);
assertSame("Configured cache not stored", analysisCache, configuration.getAnalysisCache()); assertSame("Configured cache not stored", analysisCache, configuration.getAnalysisCache());
@ -254,8 +258,7 @@ public class ConfigurationTest {
final PMDConfiguration configuration = new PMDConfiguration(); final PMDConfiguration configuration = new PMDConfiguration();
// set dummy cache location // set dummy cache location
final File cacheFile = File.createTempFile("pmd-", ".cache"); final File cacheFile = folder.newFile();
cacheFile.deleteOnExit();
final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile); final FileAnalysisCache analysisCache = new FileAnalysisCache(cacheFile);
configuration.setAnalysisCache(analysisCache); configuration.setAnalysisCache(analysisCache);
assertNotNull("Null cache location accepted", configuration.getAnalysisCache()); assertNotNull("Null cache location accepted", configuration.getAnalysisCache());

View File

@ -10,8 +10,6 @@ import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
@ -19,6 +17,7 @@ import org.junit.Assert;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
@ -39,6 +38,9 @@ public class XMLRendererTest extends AbstractRendererTest {
@Rule // Restores system properties after test @Rule // Restores system properties after test
public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Override @Override
public Renderer getRenderer() { public Renderer getRenderer() {
return new XMLRenderer(); return new XMLRenderer();
@ -160,19 +162,16 @@ public class XMLRendererTest extends AbstractRendererTest {
} }
private String renderTempFile(Renderer renderer, Report report, Charset expectedCharset) throws IOException { private String renderTempFile(Renderer renderer, Report report, Charset expectedCharset) throws IOException {
Path tempFile = Files.createTempFile("pmd-report-test", null); File reportFile = folder.newFile();
String absolutePath = tempFile.toAbsolutePath().toString();
renderer.setReportFile(absolutePath); renderer.setReportFile(reportFile.getAbsolutePath());
renderer.start(); renderer.start();
renderer.renderFileReport(report); renderer.renderFileReport(report);
renderer.end(); renderer.end();
renderer.flush(); renderer.flush();
try (FileInputStream input = new FileInputStream(absolutePath)) { try (FileInputStream input = new FileInputStream(reportFile)) {
return IOUtils.toString(input, expectedCharset); return IOUtils.toString(input, expectedCharset);
} finally {
Files.delete(tempFile);
} }
} }
} }

View File

@ -15,9 +15,10 @@ import java.util.Arrays;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import net.sourceforge.pmd.FooRule; import net.sourceforge.pmd.FooRule;
import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PMD;
@ -33,39 +34,14 @@ import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
public class YAHTMLRendererTest extends AbstractRendererTest { public class YAHTMLRendererTest extends AbstractRendererTest {
private String outputDir; private File outputDir;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
outputDir = getTemporaryDirectory("pmdtest").getAbsolutePath(); outputDir = folder.newFolder("pmdtest");
}
@After
public void cleanUp() {
deleteDirectory(new File(outputDir));
}
private File getTemporaryDirectory(String prefix) throws IOException {
// TODO: move to util class?
File dir = File.createTempFile(prefix, "");
dir.delete();
dir.mkdir();
return dir;
}
private void deleteDirectory(File dir) {
// TODO: move to util class?
File[] a = dir.listFiles();
if (a != null) {
for (File f : a) {
if (f.isDirectory()) {
deleteDirectory(f);
} else {
f.delete();
}
}
}
dir.delete();
} }
private RuleViolation newRuleViolation(int endColumn, final String packageNameArg, final String classNameArg) { private RuleViolation newRuleViolation(int endColumn, final String packageNameArg, final String classNameArg) {
@ -94,7 +70,7 @@ public class YAHTMLRendererTest extends AbstractRendererTest {
String actual = ReportTest.render(getRenderer(), report); String actual = ReportTest.render(getRenderer(), report);
assertEquals(filter(getExpected()), filter(actual)); assertEquals(filter(getExpected()), filter(actual));
String[] htmlFiles = new File(outputDir).list(); String[] htmlFiles = outputDir.list();
assertEquals(3, htmlFiles.length); assertEquals(3, htmlFiles.length);
Arrays.sort(htmlFiles); Arrays.sort(htmlFiles);
assertEquals("YAHTMLSampleClass1.html", htmlFiles[0]); assertEquals("YAHTMLSampleClass1.html", htmlFiles[0]);
@ -120,7 +96,7 @@ public class YAHTMLRendererTest extends AbstractRendererTest {
@Override @Override
public Renderer getRenderer() { public Renderer getRenderer() {
Renderer result = new YAHTMLRenderer(); Renderer result = new YAHTMLRenderer();
result.setProperty(YAHTMLRenderer.OUTPUT_DIR, outputDir); result.setProperty(YAHTMLRenderer.OUTPUT_DIR, outputDir.getAbsolutePath());
return result; return result;
} }

View File

@ -14,7 +14,9 @@ import java.util.ResourceBundle;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/** /**
* *
@ -27,6 +29,9 @@ public class DBTypeTest {
private Properties testProperties; private Properties testProperties;
private Properties includeProperties; private Properties includeProperties;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
testProperties = new Properties(); testProperties = new Properties();
@ -38,7 +43,7 @@ public class DBTypeTest {
includeProperties.putAll(testProperties); includeProperties.putAll(testProperties);
includeProperties.put("prop3", "include3"); includeProperties.put("prop3", "include3");
absoluteFile = File.createTempFile("dbtypetest", ".properties"); absoluteFile = folder.newFile();
try (FileOutputStream fileOutputStream = new FileOutputStream(absoluteFile); try (FileOutputStream fileOutputStream = new FileOutputStream(absoluteFile);
PrintStream printStream = new PrintStream(fileOutputStream)) { PrintStream printStream = new PrintStream(fileOutputStream)) {
for (Entry<?, ?> entry : testProperties.entrySet()) { for (Entry<?, ?> entry : testProperties.entrySet()) {
@ -50,7 +55,6 @@ public class DBTypeTest {
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
testProperties = null; testProperties = null;
absoluteFile.delete();
} }
/** /**

View File

@ -5,13 +5,11 @@
package net.sourceforge.pmd.it; package net.sourceforge.pmd.it;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.PMDVersion;
@ -21,6 +19,9 @@ public abstract class AbstractBinaryDistributionTest {
return new File(".", "target/pmd-bin-" + PMDVersion.VERSION + ".zip"); return new File(".", "target/pmd-bin-" + PMDVersion.VERSION + ".zip");
} }
@ClassRule
public static TemporaryFolder folder = new TemporaryFolder();
/** /**
* The temporary directory, to which the binary distribution will be extracted. * The temporary directory, to which the binary distribution will be extracted.
* It will be deleted again after the test. * It will be deleted again after the test.
@ -29,16 +30,9 @@ public abstract class AbstractBinaryDistributionTest {
@BeforeClass @BeforeClass
public static void setupTempDirectory() throws Exception { public static void setupTempDirectory() throws Exception {
tempDir = Files.createTempDirectory("pmd-it-test-"); tempDir = folder.newFolder().toPath();
if (getBinaryDistribution().exists()) { if (getBinaryDistribution().exists()) {
ZipFileExtractor.extractZipFile(getBinaryDistribution().toPath(), tempDir); ZipFileExtractor.extractZipFile(getBinaryDistribution().toPath(), tempDir);
} }
} }
@AfterClass
public static void cleanupTempDirectory() throws IOException {
if (tempDir != null && tempDir.toFile().exists()) {
FileUtils.forceDelete(tempDir.toFile());
}
}
} }

View File

@ -35,8 +35,8 @@ public class AllRulesIT extends AbstractBinaryDistributionTest {
public void runRuleTests() throws Exception { public void runRuleTests() throws Exception {
String srcDir = new File(".", "src/test/resources/sample-source/" + language + "/").getAbsolutePath(); String srcDir = new File(".", "src/test/resources/sample-source/" + language + "/").getAbsolutePath();
ExecutionResult result = PMDExecutor.runPMDRules(tempDir, srcDir, "src/test/resources/rulesets/all-" ExecutionResult result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir,
+ language + ".xml"); "src/test/resources/rulesets/all-" + language + ".xml");
assertDefaultExecutionResult(result); assertDefaultExecutionResult(result);
} }

View File

@ -84,15 +84,15 @@ public class BinaryDistributionIT extends AbstractBinaryDistributionTest {
result = PMDExecutor.runPMD(tempDir, "-h"); result = PMDExecutor.runPMD(tempDir, "-h");
result.assertExecutionResult(0, SUPPORTED_LANGUAGES_PMD); result.assertExecutionResult(0, SUPPORTED_LANGUAGES_PMD);
result = PMDExecutor.runPMDRules(tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml"); result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml");
result.assertExecutionResult(4, "", "JumbledIncrementer.java:8:"); result.assertExecutionResult(4, "", "JumbledIncrementer.java:8:");
// also test XML format // also test XML format
result = PMDExecutor.runPMDRules(tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml", "xml"); result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "src/test/resources/rulesets/sample-ruleset.xml", "xml");
result.assertExecutionResult(4, "", "JumbledIncrementer.java\">"); result.assertExecutionResult(4, "", "JumbledIncrementer.java\">");
result.assertExecutionResult(4, "", "<violation beginline=\"8\" endline=\"10\" begincolumn=\"13\" endcolumn=\"13\" rule=\"JumbledIncrementer\""); result.assertExecutionResult(4, "", "<violation beginline=\"8\" endline=\"10\" begincolumn=\"13\" endcolumn=\"13\" rule=\"JumbledIncrementer\"");
result = PMDExecutor.runPMDRules(tempDir, srcDir, "rulesets/java/quickstart.xml"); result = PMDExecutor.runPMDRules(folder.newFile().toPath(), tempDir, srcDir, "rulesets/java/quickstart.xml");
result.assertExecutionResult(4, ""); result.assertExecutionResult(4, "");
} }

View File

@ -6,7 +6,6 @@ package net.sourceforge.pmd.it;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -97,20 +96,18 @@ public class PMDExecutor {
/** /**
* Executes the PMD found in tempDir against the given sourceDirectory path with the given ruleset. * 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 tempDir the directory, to which the binary distribution has been extracted
* @param sourceDirectory the source directory, that PMD should analyze * @param sourceDirectory the source directory, that PMD should analyze
* @param ruleset the ruleset, that PMD should execute * @param ruleset the ruleset, that PMD should execute
* @return collected result of the execution * @return collected result of the execution
* @throws Exception if the execution fails for any reason (executable not found, ...) * @throws Exception if the execution fails for any reason (executable not found, ...)
*/ */
public static ExecutionResult runPMDRules(Path tempDir, String sourceDirectory, String ruleset) throws Exception { public static ExecutionResult runPMDRules(Path reportFile, Path tempDir, String sourceDirectory, String ruleset) throws Exception {
return runPMDRules(tempDir, sourceDirectory, ruleset, FORMATTER); return runPMDRules(reportFile, tempDir, sourceDirectory, ruleset, FORMATTER);
} }
public static ExecutionResult runPMDRules(Path tempDir, String sourceDirectory, String ruleset, String formatter) throws Exception { public static ExecutionResult runPMDRules(Path reportFile, Path tempDir, String sourceDirectory, String ruleset, String formatter) throws Exception {
Path reportFile = Files.createTempFile("pmd-it-report", "txt");
reportFile.toFile().deleteOnExit();
if (SystemUtils.IS_OS_WINDOWS) { if (SystemUtils.IS_OS_WINDOWS) {
return runPMDWindows(tempDir, reportFile, SOURCE_DIRECTORY_FLAG, sourceDirectory, RULESET_FLAG, ruleset, return runPMDWindows(tempDir, reportFile, SOURCE_DIRECTORY_FLAG, sourceDirectory, RULESET_FLAG, ruleset,
FORMAT_FLAG, formatter, REPORTFILE_FLAG, reportFile.toAbsolutePath().toString()); FORMAT_FLAG, formatter, REPORTFILE_FLAG, reportFile.toAbsolutePath().toString());

View File

@ -9,19 +9,17 @@ import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetFactory; import net.sourceforge.pmd.RuleSetFactory;
@ -34,11 +32,14 @@ public class RuleDocGeneratorTest {
private MockedFileWriter writer = new MockedFileWriter(); private MockedFileWriter writer = new MockedFileWriter();
private Path root; private Path root;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before @Before
public void setup() throws IOException { public void setup() throws IOException {
writer.reset(); writer.reset();
root = Files.createTempDirectory("pmd-ruledocgenerator-test"); root = folder.newFolder().toPath();
Files.createDirectories(root.resolve("docs/_data/sidebars")); Files.createDirectories(root.resolve("docs/_data/sidebars"));
List<String> mockedSidebar = Arrays.asList( List<String> mockedSidebar = Arrays.asList(
"entries:", "entries:",
@ -51,23 +52,6 @@ public class RuleDocGeneratorTest {
Files.write(root.resolve("docs/_data/sidebars/pmd_sidebar.yml"), mockedSidebar); Files.write(root.resolve("docs/_data/sidebars/pmd_sidebar.yml"), mockedSidebar);
} }
@After
public void cleanup() throws IOException {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
private static String loadResource(String name) throws IOException { private static String loadResource(String name) throws IOException {
return MockedFileWriter.normalizeLineSeparators( return MockedFileWriter.normalizeLineSeparators(
IOUtils.toString(RuleDocGeneratorTest.class.getResourceAsStream(name), StandardCharsets.UTF_8)); IOUtils.toString(RuleDocGeneratorTest.class.getResourceAsStream(name), StandardCharsets.UTF_8));

View File

@ -18,6 +18,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardErrorStreamLog; import org.junit.contrib.java.lang.system.StandardErrorStreamLog;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog; import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.rules.TemporaryFolder;
import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PMD;
@ -29,6 +30,9 @@ public class PMDCoverageTest {
@Rule @Rule
public StandardErrorStreamLog errorStream = new StandardErrorStreamLog(); public StandardErrorStreamLog errorStream = new StandardErrorStreamLog();
@Rule
public TemporaryFolder folder = new TemporaryFolder();
/** /**
* Test some of the PMD command line options * Test some of the PMD command line options
*/ */
@ -46,9 +50,8 @@ public class PMDCoverageTest {
String[] args; String[] args;
args = commandLine.split("\\s"); args = commandLine.split("\\s");
File f = null;
try { try {
f = File.createTempFile("pmd", ".txt"); File f = folder.newFile();
int n = args.length; int n = args.length;
String[] a = new String[n + 2 + 2]; String[] a = new String[n + 2 + 2];
System.arraycopy(args, 0, a, 0, n); System.arraycopy(args, 0, a, 0, n);
@ -74,10 +77,6 @@ public class PMDCoverageTest {
assertEquals("No parsing error expected", 0, StringUtils.countMatches(report, "Error while parsing")); assertEquals("No parsing error expected", 0, StringUtils.countMatches(report, "Error while parsing"));
} catch (IOException ioe) { } catch (IOException ioe) {
fail("Problem creating temporary file: " + ioe.getLocalizedMessage()); fail("Problem creating temporary file: " + ioe.getLocalizedMessage());
} finally {
if (f != null) {
f.delete();
}
} }
} }