diff --git a/pom.xml b/pom.xml index d2a87c8..8059a5d 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,7 @@ false syslog-java-client true + false @@ -118,6 +119,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + diff --git a/src/test/java/hudson/plugins/audit_trail/AuditTrailFilterTest.java b/src/test/java/hudson/plugins/audit_trail/AuditTrailFilterTest.java index 4073005..0d1560f 100644 --- a/src/test/java/hudson/plugins/audit_trail/AuditTrailFilterTest.java +++ b/src/test/java/hudson/plugins/audit_trail/AuditTrailFilterTest.java @@ -1,6 +1,6 @@ package hudson.plugins.audit_trail; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.Util; import hudson.model.Cause; @@ -8,34 +8,32 @@ import java.io.File; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.regex.Pattern; import org.htmlunit.FailingHttpStatusCodeException; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; -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 org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** - * Created by Pierre Beitz - * on 18/11/2019. + * @author Pierre Beitz */ -public class AuditTrailFilterTest { +@WithJenkins +class AuditTrailFilterTest { public static final int LONG_DELAY = 50000; - @Rule - public JenkinsRule j = new JenkinsRule(); - - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + Path tmpDir; @Test - public void cancelItemLogsTheQueryStringAndTheUser() throws Exception { - File logFile = new File(tmpDir.getRoot(), "test.log"); + void cancelItemLogsTheQueryStringAndTheUser(JenkinsRule j) throws Exception { + File logFile = tmpDir.resolve("test.log").toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); @@ -51,18 +49,18 @@ public void cancelItemLogsTheQueryStringAndTheUser() throws Exception { // see https://issues.jenkins-ci.org/browse/JENKINS-21311 } - String log = Util.loadFile(new File(tmpDir.getRoot(), "test.log.0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve("test.log.0").toFile(), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*id=1.*job/test-job.*by \\QNA from 127.0.0.1\\E.*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Issue("JENKINS-15731") @Test - public void createItemLogsTheNewItemName() throws Exception { - File logFile = new File(tmpDir.getRoot(), "create-item.log"); + void createItemLogsTheNewItemName(JenkinsRule j) throws Exception { + File logFile = tmpDir.resolve("create-item.log").toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); @@ -78,11 +76,11 @@ public void createItemLogsTheNewItemName() throws Exception { wc.waitForBackgroundJavaScript(50); j.submit(form); - String log = Util.loadFile(new File(tmpDir.getRoot(), "create-item.log.0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve("create-item.log.0").toFile(), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*createItem \\(" + jobName + "\\).*by \\QNA from 127.0.0.1\\E.*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } } diff --git a/src/test/java/hudson/plugins/audit_trail/AuditTrailPluginTest.java b/src/test/java/hudson/plugins/audit_trail/AuditTrailPluginTest.java index f01733d..6f338ce 100644 --- a/src/test/java/hudson/plugins/audit_trail/AuditTrailPluginTest.java +++ b/src/test/java/hudson/plugins/audit_trail/AuditTrailPluginTest.java @@ -1,27 +1,25 @@ package hudson.plugins.audit_trail; import static hudson.plugins.audit_trail.AuditTrailPlugin.DEFAULT_PATTERN; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import hudson.ExtensionList; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; -import org.junit.ClassRule; -import org.junit.Test; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; /** - * Created by Pierre Beitz + * @author Pierre Beitz */ -public class AuditTrailPluginTest { +@WithJenkinsConfiguredWithCode +class AuditTrailPluginTest { - @ClassRule - public static JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); - - @ConfiguredWithCode("security-1846") + @ConfiguredWithCode("security-1846.yaml") @Issue("SECURITY-1846") @Test - public void aLegacyDefaultPatternGetsReplacedByTheDefaultPattern() { + void aLegacyDefaultPatternGetsReplacedByTheDefaultPattern(JenkinsConfiguredWithCodeRule r) { ExtensionList extensionList = r.jenkins.getExtensionList(AuditTrailPlugin.class); AuditTrailPlugin plugin = extensionList.get(0); assertEquals(DEFAULT_PATTERN, plugin.getPattern()); diff --git a/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerFreestyleTest.java b/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerFreestyleTest.java index 1426fe1..b242206 100644 --- a/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerFreestyleTest.java +++ b/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerFreestyleTest.java @@ -7,11 +7,12 @@ import hudson.model.labels.LabelAtom; import java.io.File; import java.nio.charset.StandardCharsets; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.RealJenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension; /** * Created by Pierre Beitz @@ -19,17 +20,17 @@ */ public class AuditTrailRunListenerFreestyleTest { - @Rule - public RealJenkinsRule rr = new RealJenkinsRule().omitPlugins("workflow-job"); + @RegisterExtension + private final RealJenkinsExtension rr = new RealJenkinsExtension().omitPlugins("workflow-job"); - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + Path tmpDir; @Issue("JENKINS-71637") @Test public void shouldLogPerStageWorkflowRunAgentNameWithoutPipelineInstalled() throws Throwable { var logFileName = "shouldLogPerStageWorkflowRunAgentName.log"; - var rootDir = tmpDir.getRoot(); + var rootDir = tmpDir.toFile(); var logFile = new File(rootDir, logFileName); rr.startJenkins(); rr.runRemotely(j -> { @@ -46,6 +47,7 @@ public void shouldLogPerStageWorkflowRunAgentNameWithoutPipelineInstalled() thro freestyle.save(); freestyle.scheduleBuild2(0).get(); + Thread.sleep(5000); var log = Util.loadFile(new File(rootDir, logFileName + ".0"), StandardCharsets.UTF_8); assertThat(log, containsString("slave0")); }); diff --git a/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerTest.java b/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerTest.java index f11cb7d..41753d2 100644 --- a/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/AuditTrailRunListenerTest.java @@ -1,10 +1,11 @@ package hudson.plugins.audit_trail; import static hudson.plugins.audit_trail.BasicNodeNameRetriever.UNKNOWN_NODE; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -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 hudson.Util; import hudson.model.AbstractBuild; @@ -18,33 +19,31 @@ import hudson.model.StringParameterDefinition; import hudson.model.labels.LabelAtom; import java.io.File; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.regex.Pattern; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; -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 org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; /** - * Created by Pierre Beitz - * on 31/12/2019. + * @author Pierre Beitz */ -public class AuditTrailRunListenerTest { - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class AuditTrailRunListenerTest { - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + Path tmpDir; @Issue("JENKINS-12848") @Test - public void jobParametersAreProperlyLogged() throws Exception { + void jobParametersAreProperlyLogged(JenkinsRule j) throws Exception { String logFileName = "jobParametersAreProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); @@ -54,40 +53,40 @@ public void jobParametersAreProperlyLogged() throws Exception { new BooleanParameterDefinition("booleanParam", false, ""))); job.scheduleBuild2(0, new Cause.UserIdCause()).get(); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile( ".*, Parameters:\\[stringParam: \\{value1\\}, booleanParam: \\{false\\}\\].*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Issue("JENKINS-12848") @Test - public void jobWithoutParameterIsProperlyLogged() throws Exception { + void jobWithoutParameterIsProperlyLogged(JenkinsRule j) throws Exception { String logFileName = "jobWithoutParameterIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); FreeStyleProject job = j.createFreeStyleProject("test-job"); job.scheduleBuild2(0, new Cause.UserIdCause()).get(); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*, Parameters:\\[\\].*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Issue("JENKINS-12848") @Test - public void jobWithSecretParameterIsProperlyLogged() throws Exception { + void jobWithSecretParameterIsProperlyLogged(JenkinsRule j) throws Exception { String logFileName = "jobWithSecretParameterIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); @@ -96,19 +95,19 @@ public void jobWithSecretParameterIsProperlyLogged() throws Exception { new ParametersDefinitionProperty(new PasswordParameterDefinition("passParam", "thisIsASecret", ""))); job.scheduleBuild2(0, new Cause.UserIdCause()).get(); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*, Parameters:\\[passParam: \\{\\*\\*\\*\\*\\}\\].*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Issue("JENKINS-62812") @Test - public void ifSetToNotLogBuildCauseShouldNotLogThem() throws Exception { + void ifSetToNotLogBuildCauseShouldNotLogThem(JenkinsRule j) throws Exception { String logFileName = "ifSetToNotLogBuildCauseShouldNotLogThem.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile) .withLogBuildCause(false) @@ -119,13 +118,13 @@ public void ifSetToNotLogBuildCauseShouldNotLogThem() throws Exception { new ParametersDefinitionProperty(new PasswordParameterDefinition("passParam", "thisIsASecret", ""))); job.scheduleBuild2(0, new Cause.UserIdCause()).get(); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue(log.isEmpty()); } @Issue("JENKINS-71637") @Test - public void buildNodeNameIsProperlyExtractedFromTheRun() { + void buildNodeNameIsProperlyExtractedFromTheRun(JenkinsRule $) { var listener = new AuditTrailRunListener(); var notAbstractBuild = Mockito.mock(Run.class); @@ -144,9 +143,9 @@ public void buildNodeNameIsProperlyExtractedFromTheRun() { @Issue("JENKINS-71637") @Test - public void shouldWorkflowRunAgentName() throws Exception { + public void shouldWorkflowRunAgentName(JenkinsRule j) throws Exception { var logFileName = "shouldLogWorkflowRunAgentName.log"; - var logFile = new File(tmpDir.getRoot(), logFileName); + var logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile) .withLogBuildCause(true) @@ -176,7 +175,7 @@ public void shouldWorkflowRunAgentName() throws Exception { System.out.println(run.getLog()); - var log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); // the API creates agents with name slaveN assertThat(log, containsString("slave0")); @@ -184,9 +183,9 @@ public void shouldWorkflowRunAgentName() throws Exception { @Issue("JENKINS-71637") @Test - public void shouldLogPerStageWorkflowRunAgentName() throws Exception { + public void shouldLogPerStageWorkflowRunAgentName(JenkinsRule j) throws Exception { var logFileName = "shouldLogPerStageWorkflowRunAgentName.log"; - var logFile = new File(tmpDir.getRoot(), logFileName); + var logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile) .withLogBuildCause(true) @@ -223,7 +222,7 @@ public void shouldLogPerStageWorkflowRunAgentName() throws Exception { workflowJob.save(); workflowJob.scheduleBuild2(0).get(); - var log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertThat(log, containsString("Built-In Node")); // the API creates agents with name slaveN diff --git a/src/test/java/hudson/plugins/audit_trail/AuditTrailTest.java b/src/test/java/hudson/plugins/audit_trail/AuditTrailTest.java index 3e01479..a578f07 100644 --- a/src/test/java/hudson/plugins/audit_trail/AuditTrailTest.java +++ b/src/test/java/hudson/plugins/audit_trail/AuditTrailTest.java @@ -24,19 +24,20 @@ package hudson.plugins.audit_trail; import static hudson.plugins.audit_trail.LogFileAuditLogger.DEFAULT_LOG_SEPARATOR; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.Util; import hudson.model.Cause; import hudson.model.FreeStyleProject; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.File; import java.io.IOException; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import jenkins.model.GlobalConfiguration; @@ -45,10 +46,8 @@ import org.htmlunit.WebRequest; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; -import org.junit.After; -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 org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; @@ -56,75 +55,67 @@ * Test interaction of audit-trail plugin with Jenkins core. * * @author Alan Harder + * @author Pierre Beitz */ -public class AuditTrailTest { - - @Rule - public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule(); - - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); - - @After - public void tearDown() { - tmpDir.delete(); - } +@WithJenkinsConfiguredWithCode +class AuditTrailTest { @Test - public void shouldGenerateTwoAuditLogs() throws Exception { + void shouldGenerateTwoAuditLogs(JenkinsConfiguredWithCodeRule j, @TempDir Path tmpDir) throws Exception { // Given // Configure plugin - File logFile = new File(tmpDir.getRoot(), "test.log"); + File logFile = new File(tmpDir.toFile(), "test.log"); JenkinsRule.WebClient wc = j.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); AuditTrailPlugin plugin = GlobalConfiguration.all().get(AuditTrailPlugin.class); LogFileAuditLogger logger = (LogFileAuditLogger) plugin.getLoggers().get(0); - assertEquals("log path", logFile.getPath(), logger.getLog()); - assertEquals("log size", 1, logger.getLimit()); - assertEquals("log count", 2, logger.getCount()); - assertTrue("log build cause", plugin.getLogBuildCause()); - assertTrue("log credentials usage", plugin.shouldLogCredentialsUsage()); + assertEquals(logFile.getPath(), logger.getLog(), "log path"); + assertEquals(1, logger.getLimit(), "log size"); + assertEquals(2, logger.getCount(), "log count"); + assertTrue(plugin.getLogBuildCause(), "log build cause"); + assertTrue(plugin.shouldLogCredentialsUsage(), "log credentials usage"); // When - createJobAndPush(); + createJobAndPush(j); // Then - String log = Util.loadFile(new File(tmpDir.getRoot(), "test.log.0"), Charset.forName("UTF-8")); + String log = Util.loadFile(new File(tmpDir.toFile(), "test.log.0"), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".* job/test-job/ #1 Started by user" + " .*job/test-job/enable by .*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Issue("JENKINS-44129") @Test - public void shouldCorrectlyCleanUpFileHandlerOnApply() throws Exception { + void shouldCorrectlyCleanUpFileHandlerOnApply(JenkinsConfiguredWithCodeRule j, @TempDir Path tmpDir) + throws Exception { // Given JenkinsRule.WebClient wc = j.createWebClient(); HtmlPage configure = wc.goTo("configure"); HtmlForm form = configure.getFormByName("config"); // When - File logFile = new File(tmpDir.getRoot(), "unique.log"); + File logFile = new File(tmpDir.toFile(), "unique.log"); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(j, wc); // Then assertEquals( - "Only two files should be present, the file opened by the FileHandler and its lock", 2, - tmpDir.getRoot().list().length); + tmpDir.toFile().list().length, + "Only two files should be present, the file opened by the FileHandler and its lock"); } @Issue("JENKINS-60421") @Test @ConfiguredWithCode("jcasc-console-and-file.yml") - public void shouldGenerateAuditLogsWhenSetupWithJCasc() + void shouldGenerateAuditLogsWhenSetupWithJCasc(JenkinsConfiguredWithCodeRule j) throws IOException, ExecutionException, InterruptedException { // the injected jcasc assumes the temp directory is /tmp so let's skip windows assumeTrue(!System.getProperty("os.name").toLowerCase().contains("windows")); - createJobAndPush(); + createJobAndPush(j); // https://github.com/jenkinsci/configuration-as-code-plugin/issues/899#issuecomment-524641582 log is 1, not 0 // because of this. @@ -136,10 +127,10 @@ public void shouldGenerateAuditLogsWhenSetupWithJCasc() logFile.deleteOnExit(); String log = Util.loadFile(logFile, StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".* job/test-job/ #1 Started by user" + " .*job/test-job/enable by .*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); // covering the console case will require refactoring as currently the console logger is directly using // System.out/err @@ -148,18 +139,17 @@ public void shouldGenerateAuditLogsWhenSetupWithJCasc() @Issue("JENKINS-60421") @Test - public void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() - throws IOException, ExecutionException, InterruptedException { + void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() throws IOException { // the injected xml assumes the temp directory is /tmp so let's skip windows assumeTrue(!System.getProperty("os.name").toLowerCase().contains("windows")); AuditTrailPlugin plugin = load("sample.xml", getClass()); LogFileAuditLogger logger = (LogFileAuditLogger) plugin.getLoggers().get(0); - assertEquals("log path", "/tmp/xml-logs", logger.getLog()); - assertEquals("log size", 100, logger.getLimit()); - assertEquals("log count", 5, logger.getCount()); - assertEquals("log separator", DEFAULT_LOG_SEPARATOR, logger.getLogSeparator()); - assertTrue("log build cause", plugin.getLogBuildCause()); + assertEquals("/tmp/xml-logs", logger.getLog(), "log path"); + assertEquals(100, logger.getLimit(), "log size"); + assertEquals(5, logger.getCount(), "log count"); + assertEquals(DEFAULT_LOG_SEPARATOR, logger.getLogSeparator(), "log separator"); + assertTrue(plugin.getLogBuildCause(), "log build cause"); String message = "hello"; plugin.getLoggers().get(0).log(message); @@ -167,7 +157,7 @@ public void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() File logFile = new File("/tmp", "xml-logs.0"); logFile.deleteOnExit(); String log = Util.loadFile(logFile, StandardCharsets.UTF_8); - assertTrue("logged actions: " + log, log.contains(message)); + assertTrue(log.contains(message), () -> "logged actions: " + log); // covering the console case will require refactoring as currently the console logger is directly using // System.out/err @@ -178,7 +168,8 @@ static AuditTrailPlugin load(String fileName, Class clasz) { return (AuditTrailPlugin) Jenkins.XSTREAM2.fromXML(clasz.getResource(fileName)); } - private void createJobAndPush() throws IOException, InterruptedException, ExecutionException { + private void createJobAndPush(JenkinsConfiguredWithCodeRule j) + throws IOException, InterruptedException, ExecutionException { FreeStyleProject job = j.createFreeStyleProject("test-job"); job.scheduleBuild2(0, new Cause.UserIdCause()).get(); JenkinsRule.WebClient wc = j.createWebClient(); diff --git a/src/test/java/hudson/plugins/audit_trail/BypassablePatternMonitorTest.java b/src/test/java/hudson/plugins/audit_trail/BypassablePatternMonitorTest.java index 4a3e09c..9523725 100644 --- a/src/test/java/hudson/plugins/audit_trail/BypassablePatternMonitorTest.java +++ b/src/test/java/hudson/plugins/audit_trail/BypassablePatternMonitorTest.java @@ -1,21 +1,21 @@ package hudson.plugins.audit_trail; -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 static org.mockito.Mockito.when; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.Issue; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** * Created by Pierre Beitz */ -@RunWith(MockitoJUnitRunner.class) -public class BypassablePatternMonitorTest { +@ExtendWith(MockitoExtension.class) +class BypassablePatternMonitorTest { @Mock private AuditTrailPlugin plugin; @@ -25,28 +25,28 @@ public class BypassablePatternMonitorTest { @Issue("SECURITY-1846") @Test - public void aProperlyProtectedPatternShouldNotTriggerTheMonitor() { + void aProperlyProtectedPatternShouldNotTriggerTheMonitor() { when(plugin.getPattern()).thenReturn(".*/configSubmit/?.*"); assertFalse(monitor.isActivated()); } @Issue("SECURITY-1846") @Test - public void aSuffixVulnerablePatternShouldTriggerTheMonitor() { + void aSuffixVulnerablePatternShouldTriggerTheMonitor() { when(plugin.getPattern()).thenReturn(".*/configSubmit"); assertTrue(monitor.isActivated()); } @Issue("SECURITY-1846") @Test - public void aPrefixVulnerablePatternShouldTriggerTheMonitor() { + void aPrefixVulnerablePatternShouldTriggerTheMonitor() { when(plugin.getPattern()).thenReturn("/configSubmit/?.*"); assertTrue(monitor.isActivated()); } @Issue("SECURITY-1846") @Test - public void aPrefixAndSuffixVulnerablePatternShouldTriggerTheMonitor() { + void aPrefixAndSuffixVulnerablePatternShouldTriggerTheMonitor() { when(plugin.getPattern()).thenReturn("/configSubmit"); assertTrue(monitor.isActivated()); } diff --git a/src/test/java/hudson/plugins/audit_trail/ConfigurationAsCodeTest.java b/src/test/java/hudson/plugins/audit_trail/ConfigurationAsCodeTest.java index 25dd503..fa53acf 100644 --- a/src/test/java/hudson/plugins/audit_trail/ConfigurationAsCodeTest.java +++ b/src/test/java/hudson/plugins/audit_trail/ConfigurationAsCodeTest.java @@ -2,31 +2,30 @@ import static io.jenkins.plugins.casc.misc.Util.*; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.ExtensionList; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import io.jenkins.plugins.casc.model.CNode; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; /** - * Created by Pierre Beitz - * on 2019-07-20. + * @author Pierre Beitz */ -public class ConfigurationAsCodeTest { - - @ClassRule - @ConfiguredWithCode("jcasc.yml") - public static JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); +@WithJenkinsConfiguredWithCode +class ConfigurationAsCodeTest { @Issue("JENKINS-57232") @Test - public void should_support_configuration_as_code() { + @ConfiguredWithCode("jcasc.yml") + void shouldSupportConfigurationAsCode(JenkinsConfiguredWithCodeRule r) { ExtensionList extensionList = r.jenkins.getExtensionList(AuditTrailPlugin.class); AuditTrailPlugin plugin = extensionList.get(0); assertEquals( @@ -64,7 +63,8 @@ public void should_support_configuration_as_code() { @Issue("JENKINS-57232") @Test - public void should_support_configuration_export() throws Exception { + @ConfiguredWithCode("jcasc.yml") + public void should_support_configuration_export(JenkinsConfiguredWithCodeRule r) throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); CNode auditTrailAttribute = getUnclassifiedRoot(context).get("audit-trail"); diff --git a/src/test/java/hudson/plugins/audit_trail/ConsoleAuditLoggerTest.java b/src/test/java/hudson/plugins/audit_trail/ConsoleAuditLoggerTest.java index 7fc559d..217c825 100644 --- a/src/test/java/hudson/plugins/audit_trail/ConsoleAuditLoggerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/ConsoleAuditLoggerTest.java @@ -24,9 +24,10 @@ package hudson.plugins.audit_trail; import static hudson.plugins.audit_trail.AuditTrailTest.load; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.Util; import java.io.File; @@ -35,23 +36,21 @@ import jenkins.model.GlobalConfiguration; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Tomasz Sęk * @author Pierre Beitz */ -public class ConsoleAuditLoggerTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class ConsoleAuditLoggerTest { @Issue("JENKINS-51331") @Test - public void shouldConfigureConsoleAuditLogger() throws Exception { + void shouldConfigureConsoleAuditLogger(JenkinsRule j) throws Exception { // Given JenkinsRule.WebClient wc = j.createWebClient(); HtmlPage configure = wc.goTo("configure"); @@ -66,22 +65,22 @@ public void shouldConfigureConsoleAuditLogger() throws Exception { // Then // submit configuration page without any errors AuditTrailPlugin plugin = GlobalConfiguration.all().get(AuditTrailPlugin.class); - assertEquals("amount of loggers", 1, plugin.getLoggers().size()); + assertEquals(1, plugin.getLoggers().size(), "amount of loggers"); AuditLogger logger = plugin.getLoggers().get(0); - assertTrue("ConsoleAuditLogger should be configured", logger instanceof ConsoleAuditLogger); - assertEquals("output", ConsoleAuditLogger.Output.STD_OUT, ((ConsoleAuditLogger) logger).getOutput()); + assertInstanceOf(ConsoleAuditLogger.class, logger, "ConsoleAuditLogger should be configured"); + assertEquals(ConsoleAuditLogger.Output.STD_OUT, ((ConsoleAuditLogger) logger).getOutput(), "output"); } @Issue("JENKINS-12848") @Test - public void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() throws IOException { + void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() throws IOException { // the injected xml assumes the temp directory is /tmp so let's skip windows assumeTrue(!System.getProperty("os.name").toLowerCase().contains("windows")); AuditTrailPlugin plugin = load("jenkins-12848.xml", getClass()); LogFileAuditLogger logger = (LogFileAuditLogger) plugin.getLoggers().get(0); String logSeparator = ";"; - assertEquals("log separator", logSeparator, logger.getLogSeparator()); + assertEquals(logSeparator, logger.getLogSeparator(), "log separator"); String message = "hello"; plugin.getLoggers().get(0).log(message); @@ -89,6 +88,6 @@ public void loggerShouldBeProperlyConfiguredWhenLoadedFromXml() throws IOExcepti File logFile = new File("/tmp", "xml-logs-12848.0"); logFile.deleteOnExit(); String log = Util.loadFile(logFile, StandardCharsets.UTF_8); - assertTrue("logged actions: " + log, log.contains(logSeparator + message)); + assertTrue(log.contains(logSeparator + message), () -> "logged actions: " + log); } } diff --git a/src/test/java/hudson/plugins/audit_trail/CredentialUsageListenerTest.java b/src/test/java/hudson/plugins/audit_trail/CredentialUsageListenerTest.java index bb4d074..592d9c4 100644 --- a/src/test/java/hudson/plugins/audit_trail/CredentialUsageListenerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/CredentialUsageListenerTest.java @@ -1,6 +1,6 @@ package hudson.plugins.audit_trail; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsProvider; @@ -12,23 +12,23 @@ import hudson.slaves.DumbSlave; import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.regex.Pattern; -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 org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class CredentialUsageListenerTest { - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class CredentialUsageListenerTest { - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + Path tmpDir; @Test - public void jobCredentialUsageIsLogged() throws Exception { + void jobCredentialUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "jobCredentialUsageIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = new File(tmpDir.toFile(), logFileName); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); @@ -38,18 +38,18 @@ public void jobCredentialUsageIsLogged() throws Exception { new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description", "username", "password"); CredentialsProvider.track(job, creds); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(new File(tmpDir.toFile(), logFileName + ".0"), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*test-job.*used credentials '" + id + "'.*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Test - public void nodeCredentialUsageIsLogged() throws Exception { + void nodeCredentialUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "nodeCredentialUsageIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = new File(tmpDir.toFile(), logFileName); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); @@ -60,18 +60,18 @@ public void nodeCredentialUsageIsLogged() throws Exception { new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description", "username", "password"); CredentialsProvider.track(dummyAgent, creds); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(new File(tmpDir.toFile(), logFileName + ".0"), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*test-agent.*used credentials '" + id + "'.*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Test - public void itemCredentialUsageIsLogged() throws Exception { + void itemCredentialUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "itemCredentialUsageIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = new File(tmpDir.toFile(), logFileName); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); // 'Folder' because it is a non-traditional item to access credentials. @@ -81,18 +81,18 @@ public void itemCredentialUsageIsLogged() throws Exception { Credentials creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description", "username", "password"); CredentialsProvider.track(item, creds); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(new File(tmpDir.toFile(), logFileName + ".0"), StandardCharsets.UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile(".*test-item.*used credentials '" + id + "'.*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + () -> "logged actions: " + log); } @Test - public void disabledLoggingOptionIsRespected() throws Exception { + void disabledLoggingOptionIsRespected(JenkinsRule r) throws Exception { String logFileName = "disabledCredentialUsageIsRespected.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = new File(tmpDir.toFile(), logFileName); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile) .withLogCredentialsUsage(false) @@ -104,7 +104,7 @@ public void disabledLoggingOptionIsRespected() throws Exception { new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description", "username", "password"); CredentialsProvider.track(job, creds); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + String log = Util.loadFile(new File(tmpDir.toFile(), logFileName + ".0"), StandardCharsets.UTF_8); assertTrue(log.isEmpty()); } } diff --git a/src/test/java/hudson/plugins/audit_trail/ElasticSearchAuditLoggerTest.java b/src/test/java/hudson/plugins/audit_trail/ElasticSearchAuditLoggerTest.java index e85c9a2..83ff6b8 100644 --- a/src/test/java/hudson/plugins/audit_trail/ElasticSearchAuditLoggerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/ElasticSearchAuditLoggerTest.java @@ -1,27 +1,28 @@ package hudson.plugins.audit_trail; -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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import jenkins.model.GlobalConfiguration; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Alex Russell + * @author Pierre Beitz */ -public class ElasticSearchAuditLoggerTest { +@WithJenkins +class ElasticSearchAuditLoggerTest { - private static String esUrl = "https://localhost/myindex/jenkins"; - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + private static final String ES_URL = "https://localhost/myindex/jenkins"; @Test - public void shouldConfigureElasticSearchAuditLogger() throws Exception { + void shouldConfigureElasticSearchAuditLogger(JenkinsRule jenkinsRule) throws Exception { JenkinsRule.WebClient jenkinsWebClient = jenkinsRule.createWebClient(); HtmlPage configure = jenkinsWebClient.goTo("configure"); HtmlForm form = configure.getFormByName("config"); @@ -35,17 +36,17 @@ public void shouldConfigureElasticSearchAuditLogger() throws Exception { // Then // submit configuration page without any errors AuditTrailPlugin plugin = GlobalConfiguration.all().get(AuditTrailPlugin.class); - assertEquals("amount of loggers", 1, plugin.getLoggers().size()); + assertEquals(1, plugin.getLoggers().size(), "amount of loggers"); AuditLogger logger = plugin.getLoggers().get(0); - assertTrue("ConsoleAuditLogger should be configured", logger instanceof ElasticSearchAuditLogger); + assertInstanceOf(ElasticSearchAuditLogger.class, logger, "ConsoleAuditLogger should be configured"); } @Test - public void testElasticSearchAuditLogger() throws Exception { - ElasticSearchAuditLogger auditLogger = new ElasticSearchAuditLogger(esUrl, true); + void testElasticSearchAuditLogger() { + ElasticSearchAuditLogger auditLogger = new ElasticSearchAuditLogger(ES_URL, true); auditLogger.configure(); - assertTrue(auditLogger.getElasticSearchSender() != null); - assertEquals(esUrl, auditLogger.getElasticSearchSender().getUrl()); - assertEquals(true, auditLogger.getElasticSearchSender().getSkipCertificateValidation()); + assertNotNull(auditLogger.getElasticSearchSender()); + assertEquals(ES_URL, auditLogger.getElasticSearchSender().getUrl()); + assertTrue(auditLogger.getElasticSearchSender().getSkipCertificateValidation()); } } diff --git a/src/test/java/hudson/plugins/audit_trail/LogFileAuditLoggerTest.java b/src/test/java/hudson/plugins/audit_trail/LogFileAuditLoggerTest.java index 4711e02..6a50ae8 100644 --- a/src/test/java/hudson/plugins/audit_trail/LogFileAuditLoggerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/LogFileAuditLoggerTest.java @@ -1,41 +1,36 @@ package hudson.plugins.audit_trail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import hudson.EnvVars; import java.nio.file.Path; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; /** - * Created by Pierre Beitz - * on 2019-05-05. + * @author Pierre Beitz */ -public class LogFileAuditLoggerTest { - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); +class LogFileAuditLoggerTest { - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); + @TempDir + Path folder; @Issue("JENKINS-56108") @Test - public void configuringAFileLoggerWithNonExistingParents() { - Path logFile = folder.getRoot().toPath().resolve("subdirectory").resolve("file"); + void configuringAFileLoggerWithNonExistingParents() { + Path logFile = folder.resolve("subdirectory").resolve("file"); new LogFileAuditLogger(logFile.toString(), 5, 1, null); - Assert.assertTrue(logFile.toFile().exists()); + assertTrue(logFile.toFile().exists()); } @Issue("JENKINS-67493") @Test - public void environmentVariablesAreProperlyExpanded() { - Path rootFolder = folder.getRoot().toPath(); + void environmentVariablesAreProperlyExpanded() { EnvVars.masterEnvVars.put("EXPAND_ME", "expandMe"); - String logFile = rootFolder.resolve("${EXPAND_ME}").toString(); + String logFile = folder.resolve("${EXPAND_ME}").toString(); LogFileAuditLogger logger = new LogFileAuditLogger(logFile, 5, 1, null); - Assert.assertEquals(rootFolder.resolve("expandMe").toString(), logger.getLog()); + assertEquals(folder.resolve("expandMe").toString(), logger.getLog()); } } diff --git a/src/test/java/hudson/plugins/audit_trail/LogFileDailyRotationAuditLoggerTest.java b/src/test/java/hudson/plugins/audit_trail/LogFileDailyRotationAuditLoggerTest.java index 272503f..3ce1576 100644 --- a/src/test/java/hudson/plugins/audit_trail/LogFileDailyRotationAuditLoggerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/LogFileDailyRotationAuditLoggerTest.java @@ -1,6 +1,9 @@ package hudson.plugins.audit_trail; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.Util; import java.io.File; @@ -12,45 +15,42 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; -import org.junit.Assert; -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 org.mockito.Answers; import org.mockito.MockedStatic; import org.mockito.Mockito; -public class LogFileDailyRotationAuditLoggerTest { +class LogFileDailyRotationAuditLoggerTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + Path folder; /** * Ensures that if Daily Rotation is enabled a subdirectory with the corresponded logger * file gets created */ @Test - public void configuringAFileLoggerWithDailyRotationAndNonExistingParents() { - Path logFile = folder.getRoot().toPath().resolve("subdirectory").resolve("file"); + void configuringAFileLoggerWithDailyRotationAndNonExistingParents() { + Path logFile = folder.resolve("subdirectory").resolve("file"); LogFileDailyRotationAuditLogger logFileAuditLogger = new LogFileDailyRotationAuditLogger(logFile.toString(), 1, null); - Path logFileRotating = - folder.getRoot().toPath().resolve("subdirectory").resolve(logFileAuditLogger.computePattern()); - Assert.assertFalse(logFile.toFile().exists()); - Assert.assertTrue(logFileRotating.toFile().exists()); + Path logFileRotating = folder.resolve("subdirectory").resolve(logFileAuditLogger.computePattern()); + assertFalse(logFile.toFile().exists()); + assertTrue(logFileRotating.toFile().exists()); } /** * A test that ensures that the logger reuses the same file if restarted within the same day */ @Test - public void logFileIsReusedIfRestartedWithDailyRotation() throws IOException { - Path logFile = folder.getRoot().toPath().resolve("file"); + void logFileIsReusedIfRestartedWithDailyRotation() throws IOException { + Path logFile = folder.resolve("file"); LogFileDailyRotationAuditLogger logFileAuditLogger = new LogFileDailyRotationAuditLogger(logFile.toString(), 0, null); logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line1"); - Path logFileRotating = folder.getRoot().toPath().resolve(logFileAuditLogger.computePattern()); - Assert.assertTrue(logFileRotating.toFile().exists()); + Path logFileRotating = folder.resolve(logFileAuditLogger.computePattern()); + assertTrue(logFileRotating.toFile().exists()); logFileAuditLogger.cleanUp(); LogFileDailyRotationAuditLogger logFileAuditLogger2 = new LogFileDailyRotationAuditLogger(logFile.toString(), 0, null); @@ -62,18 +62,18 @@ public void logFileIsReusedIfRestartedWithDailyRotation() throws IOException { new RegexFileFilter(".*" + logFile.toFile().getName() + LogFileDailyRotationAuditLogger.DAILY_ROTATING_FILE_REGEX_PATTERN), DirectoryFileFilter.DIRECTORY); - Assert.assertEquals(directoryFiles.size(), 1); + assertEquals(1, directoryFiles.size()); String log = Util.loadFile(logFileRotating.toFile(), StandardCharsets.UTF_8); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line1")); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line1")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); } /** * A test that ensures that the log file rotates in the next day */ @Test - public void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOException { + void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOException { ZonedDateTime zonedDateTime1 = ZonedDateTime.now(); ZonedDateTime zonedDateTime2 = zonedDateTime1.plusDays(1); @@ -81,12 +81,12 @@ public void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOExcepti ZonedDateTime.class, Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS))) { mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime1); // Check that the log file is created with the corresponded format (Today date) - Path logFile = folder.getRoot().toPath().resolve("file"); + Path logFile = folder.resolve("file"); LogFileDailyRotationAuditLogger logFileAuditLogger = new LogFileDailyRotationAuditLogger(logFile.toString(), 2, null); logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line1"); - Path logFileRotating = folder.getRoot().toPath().resolve(logFileAuditLogger.computePattern()); - Assert.assertTrue(logFileRotating.toFile().exists()); + Path logFileRotating = folder.resolve(logFileAuditLogger.computePattern()); + assertTrue(logFileRotating.toFile().exists()); // Check that there is ONLY one file generated at this point (Today date) String directoryPath = logFile.toFile().getParent(); @@ -95,11 +95,11 @@ public void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOExcepti new RegexFileFilter(".*" + logFile.toFile().getName() + LogFileDailyRotationAuditLogger.DAILY_ROTATING_FILE_REGEX_PATTERN), DirectoryFileFilter.DIRECTORY); - Assert.assertEquals(directoryFiles.size(), 1); + assertEquals(1, directoryFiles.size()); // Log something and check it appears in the logger file String log = Util.loadFile(logFileRotating.toFile(), StandardCharsets.UTF_8); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line1")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line1")); // Increase +1 day mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime2); @@ -108,10 +108,10 @@ public void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOExcepti logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line2"); // Check that the corresponded is the ONLY one which appear on this file (Today +1) - logFileRotating = folder.getRoot().toPath().resolve(logFileAuditLogger.computePattern()); + logFileRotating = folder.resolve(logFileAuditLogger.computePattern()); log = Util.loadFile(logFileRotating.toFile(), StandardCharsets.UTF_8); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); - Assert.assertFalse(log.contains("configuringAFileLoggerRotatingDaily - line1")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); + assertFalse(log.contains("configuringAFileLoggerRotatingDaily - line1")); } } @@ -119,7 +119,7 @@ public void logFileProperlyRotatingInNextDayWithDailyRotation() throws IOExcepti * A test that ensures that old files get removed after rotation */ @Test - public void oldLogFilesProperlyRemovedWithDailyRotation() throws IOException { + void oldLogFilesProperlyRemovedWithDailyRotation() throws IOException { // test seems to be flaky on Windows, let's skip it for now I have no Windows machine to debug assumeTrue(!System.getProperty("os.name").toLowerCase().contains("windows")); ZonedDateTime zonedDateTime1 = ZonedDateTime.now(); @@ -129,43 +129,37 @@ public void oldLogFilesProperlyRemovedWithDailyRotation() throws IOException { try (MockedStatic mockedLocalDateTime = Mockito.mockStatic( ZonedDateTime.class, Mockito.withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS))) { mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime1); - Path logFile = folder.getRoot().toPath().resolve("file"); + Path logFile = folder.resolve("file"); LogFileDailyRotationAuditLogger logFileAuditLogger = new LogFileDailyRotationAuditLogger(logFile.toString(), 2, null); // Today: Log something logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line1"); - File logFileRotating1 = folder.getRoot() - .toPath() - .resolve(logFileAuditLogger.computePattern()) - .toFile(); + File logFileRotating1 = + folder.resolve(logFileAuditLogger.computePattern()).toFile(); // Today+1 Log something mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime2); logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line2"); - File logFileRotating2 = folder.getRoot() - .toPath() - .resolve(logFileAuditLogger.computePattern()) - .toFile(); + File logFileRotating2 = + folder.resolve(logFileAuditLogger.computePattern()).toFile(); // Today+2 Log something mockedLocalDateTime.when(ZonedDateTime::now).thenReturn(zonedDateTime3); logFileAuditLogger.log("configuringAFileLoggerRotatingDaily - line3"); - File logFileRotating3 = folder.getRoot() - .toPath() - .resolve(logFileAuditLogger.computePattern()) - .toFile(); + File logFileRotating3 = + folder.resolve(logFileAuditLogger.computePattern()).toFile(); // Check that the oldest file got removed after rotation - Assert.assertFalse(logFileRotating1.exists()); - Assert.assertTrue(logFileRotating2.exists()); - Assert.assertTrue(logFileRotating3.exists()); + assertFalse(logFileRotating1.exists()); + assertTrue(logFileRotating2.exists()); + assertTrue(logFileRotating3.exists()); // Check that that files contains their expected content String log = Util.loadFile(logFileRotating2, StandardCharsets.UTF_8); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line2")); log = Util.loadFile(logFileRotating3, StandardCharsets.UTF_8); - Assert.assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line3")); + assertTrue(log.contains("configuringAFileLoggerRotatingDaily - line3")); // Check that there are only two log files String directoryPath = logFile.toFile().getParent(); @@ -174,7 +168,7 @@ public void oldLogFilesProperlyRemovedWithDailyRotation() throws IOException { new RegexFileFilter(".*" + logFile.toFile().getName() + LogFileDailyRotationAuditLogger.DAILY_ROTATING_FILE_REGEX_PATTERN), DirectoryFileFilter.DIRECTORY); - Assert.assertEquals(directoryFiles.size(), 2); + assertEquals(2, directoryFiles.size()); } } } diff --git a/src/test/java/hudson/plugins/audit_trail/ScriptUsageListenerTest.java b/src/test/java/hudson/plugins/audit_trail/ScriptUsageListenerTest.java index 62b0a6a..a32c9ff 100644 --- a/src/test/java/hudson/plugins/audit_trail/ScriptUsageListenerTest.java +++ b/src/test/java/hudson/plugins/audit_trail/ScriptUsageListenerTest.java @@ -1,6 +1,7 @@ package hudson.plugins.audit_trail; -import static org.junit.Assert.assertTrue; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -11,30 +12,30 @@ import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Locale; import java.util.regex.Pattern; import javax.servlet.RequestDispatcher; -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 org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; +@WithJenkins public class ScriptUsageListenerTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + Path tmpDir; private final String script = "println('light of the world')"; @Test - public void consoleUsageIsLogged() throws Exception { + void consoleUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "consoleUsageIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); @@ -47,21 +48,21 @@ public void consoleUsageIsLogged() throws Exception { when(req.getView(r.jenkins, "_scriptText.jelly")).thenReturn(view); r.jenkins.doScriptText(req, rsp); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile( ".*A groovy script was executed by user 'SYSTEM'\\. Origin: Script Console Controller\\..*The " + "executed script:.*" + Pattern.quote(script) + ".*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + "logged actions: " + log); } @Test - public void groovyCliUsageIsLogged() throws Exception { + void groovyCliUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "cliUsageIsProperlyLogged.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); @@ -70,21 +71,21 @@ public void groovyCliUsageIsLogged() throws Exception { InputStream scriptStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)); cmd.main(new ArrayList<>(), Locale.ENGLISH, scriptStream, System.out, System.err); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile( ".*A groovy script was executed\\. Origin: CLI/GroovyCommand.*The executed script:.*" + Pattern.quote(script) + ".*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + "logged actions: " + log); } @Test - public void groovyShCliUsageIsLogged() throws Exception { + void groovyShCliUsageIsLogged(JenkinsRule r) throws Exception { String logFileName = "cliUsageIsProperlyLogged2.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile).sendConfiguration(r, wc); @@ -92,21 +93,21 @@ public void groovyShCliUsageIsLogged() throws Exception { InputStream scriptStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)); cmd.main(new ArrayList<>(), Locale.ENGLISH, scriptStream, System.out, System.err); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue( - "logged actions: " + log, Pattern.compile( ".*A groovy script was executed\\. Origin: CLI/GroovySh.*The executed script:.*" + Pattern.quote(script) + ".*", Pattern.DOTALL) .matcher(log) - .matches()); + .matches(), + "logged actions: " + log); } @Test - public void disabledLoggingOptionIsRespected() throws Exception { + void disabledLoggingOptionIsRespected(JenkinsRule r) throws Exception { String logFileName = "disabledCredentialUsageIsRespected.log"; - File logFile = new File(tmpDir.getRoot(), logFileName); + File logFile = tmpDir.resolve(logFileName).toFile(); JenkinsRule.WebClient wc = r.createWebClient(); new SimpleAuditTrailPluginConfiguratorHelper(logFile) .withLogScriptUsage(false) @@ -117,7 +118,7 @@ public void disabledLoggingOptionIsRespected() throws Exception { InputStream scriptStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)); cmd.main(new ArrayList<>(), Locale.ENGLISH, scriptStream, System.out, System.err); - String log = Util.loadFile(new File(tmpDir.getRoot(), logFileName + ".0"), StandardCharsets.UTF_8); + var log = Util.loadFile(tmpDir.resolve(logFileName + ".0").toFile(), UTF_8); assertTrue(log.isEmpty()); } }