From 8eae87ed3e6627f39b911c062728e022b2a77a5b Mon Sep 17 00:00:00 2001 From: strangelookingnerd Date: Mon, 17 Feb 2025 13:39:07 +0100 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor clean up --- .../platformlabeler/ConfigurationTest.java | 32 +++---- .../platformlabeler/LabelConfigTest.java | 46 +++++----- .../LsbReleaseFakeFileTest.java | 8 +- .../platformlabeler/LsbReleaseFakeTest.java | 8 +- .../platformlabeler/LsbReleaseRealTest.java | 2 +- .../platformlabeler/NodeLabelCacheTest.java | 89 ++++++++++--------- .../PlatformDetailsCheckRolesTest.java | 34 ++++--- .../PlatformDetailsTaskLsbReleaseTest.java | 4 +- .../PlatformDetailsTaskReleaseTest.java | 4 +- .../PlatformDetailsTaskStaticStringTest.java | 26 +++--- .../PlatformDetailsTaskTest.java | 29 +++--- ...PlatformDetailsTaskWindowsReleaseTest.java | 4 +- .../platformlabeler/PlatformDetailsTest.java | 20 ++--- .../platformlabeler/PlatformLabelerTest.java | 18 ++-- .../platformlabeler/WindowsReleaseTest.java | 15 ++-- 15 files changed, 168 insertions(+), 171 deletions(-) diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/ConfigurationTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/ConfigurationTest.java index 2be026d8c..c15d9e805 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/ConfigurationTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/ConfigurationTest.java @@ -14,28 +14,30 @@ import java.util.HashSet; import java.util.Set; import jenkins.model.GlobalConfiguration; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class ConfigurationTest { - @Rule - public final JenkinsRule r = new JenkinsRule(); +@WithJenkins +class ConfigurationTest { + + private JenkinsRule r; private Computer computer; private NodeLabelCache nodeLabelCache; private PlatformDetails platformDetails; - @Before - public void setUp() throws IOException, InterruptedException { + @BeforeEach + void setUp(JenkinsRule r) throws IOException, InterruptedException { + this.r = r; computer = r.jenkins.toComputer(); nodeLabelCache = ComputerListener.all().get(NodeLabelCache.class); platformDetails = nodeLabelCache.requestComputerPlatformDetails(computer, computer.getChannel()); } @Test - public void configuredNameOnlyLabel() { + void configuredNameOnlyLabel() { PlatformLabelerNodeProperty nodeProperty = new PlatformLabelerNodeProperty(); LabelConfig labelConfig = new LabelConfig(); labelConfig.setArchitecture(false); @@ -59,7 +61,7 @@ public void configuredNameOnlyLabel() { } @Test - public void configuredTwoLabels() { + void configuredTwoLabels() { PlatformLabelerNodeProperty nodeProperty = new PlatformLabelerNodeProperty(); LabelConfig labelConfig = new LabelConfig(); labelConfig.setArchitectureName(false); @@ -83,7 +85,7 @@ public void configuredTwoLabels() { } @Test - public void configuredAllLabelsOnEphemeralNode() throws Exception { + void configuredAllLabelsOnEphemeralNode() throws Exception { // Create and connect the agent DumbSlave agent = r.createSlave(Label.get("agent")); @@ -125,7 +127,7 @@ public void configuredAllLabelsOnEphemeralNode() throws Exception { } @Test - public void configuredAllLabelsOnNode() { + void configuredAllLabelsOnNode() { PlatformLabelerNodeProperty nodeProperty = new PlatformLabelerNodeProperty(); LabelConfig labelConfig = new LabelConfig(); nodeProperty.setLabelConfig(labelConfig); @@ -155,7 +157,7 @@ public void configuredAllLabelsOnNode() { } @Test - public void nodeConfigOverridesGlobalConfig() { + void nodeConfigOverridesGlobalConfig() { PlatformLabelerGlobalConfiguration globalConfig = GlobalConfiguration.all().getInstance(PlatformLabelerGlobalConfiguration.class); @@ -190,7 +192,7 @@ public void nodeConfigOverridesGlobalConfig() { } @Test - public void globalConfigOnlyArchitecture() { + void globalConfigOnlyArchitecture() { PlatformLabelerGlobalConfiguration globalConfig = GlobalConfiguration.all().getInstance(PlatformLabelerGlobalConfiguration.class); @@ -218,7 +220,7 @@ public void globalConfigOnlyArchitecture() { } @Test - public void configRoundTripTest() throws Exception { + void configRoundTripTest() throws Exception { PlatformLabelerGlobalConfiguration globalConfig = GlobalConfiguration.all().getInstance(PlatformLabelerGlobalConfiguration.class); LabelConfig globalLabelConfigBefore = globalConfig.getLabelConfig(); diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LabelConfigTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LabelConfigTest.java index 712dc3761..3495dde2e 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LabelConfigTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LabelConfigTest.java @@ -4,10 +4,10 @@ import static org.hamcrest.Matchers.is; import java.util.Random; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class LabelConfigTest { +class LabelConfigTest { private final Random random = new Random(); @@ -23,10 +23,8 @@ public class LabelConfigTest { private boolean randomIsWindowsFeatureUpdate; private boolean randomIsOsName; - public LabelConfigTest() {} - - @Before - public void setUp() { + @BeforeEach + void setUp() { LabelConfig randomSrcLabelConfig = new LabelConfig(); randomIsArchitecture = random.nextBoolean(); @@ -52,7 +50,7 @@ public void setUp() { } @Test - public void testConstructorNullArg() { + void testConstructorNullArg() { LabelConfig nullLabelConfig = new LabelConfig(null); assertThat(nullLabelConfig.isArchitecture(), is(defaultConfig.isArchitecture())); assertThat(nullLabelConfig.isName(), is(defaultConfig.isName())); @@ -63,97 +61,97 @@ public void testConstructorNullArg() { } @Test - public void testIsArchitecture() { + void testIsArchitecture() { assertThat(defaultConfig.isArchitecture(), is(true)); assertThat(randomConfig.isArchitecture(), is(randomIsArchitecture)); } @Test - public void testSetArchitecture() { + void testSetArchitecture() { defaultConfig.setArchitecture(!randomIsArchitecture); assertThat(defaultConfig.isArchitecture(), is(!randomIsArchitecture)); } @Test - public void testIsName() { + void testIsName() { assertThat(defaultConfig.isName(), is(true)); assertThat(randomConfig.isName(), is(randomIsName)); } @Test - public void testSetName() { + void testSetName() { defaultConfig.setName(!randomIsName); assertThat(defaultConfig.isName(), is(!randomIsName)); } @Test - public void testIsVersion() { + void testIsVersion() { assertThat(defaultConfig.isVersion(), is(true)); assertThat(randomConfig.isVersion(), is(randomIsVersion)); } @Test - public void testSetVersion() { + void testSetVersion() { defaultConfig.setVersion(!randomIsVersion); assertThat(defaultConfig.isVersion(), is(!randomIsVersion)); } @Test - public void testIsArchitectureName() { + void testIsArchitectureName() { assertThat(defaultConfig.isArchitectureName(), is(true)); assertThat(randomConfig.isArchitectureName(), is(randomIsArchitectureName)); } @Test - public void testSetArchitectureName() { + void testSetArchitectureName() { defaultConfig.setArchitectureName(!randomIsArchitectureName); assertThat(defaultConfig.isArchitectureName(), is(!randomIsArchitectureName)); } @Test - public void testIsNameVersion() { + void testIsNameVersion() { assertThat(defaultConfig.isNameVersion(), is(true)); assertThat(randomConfig.isNameVersion(), is(randomIsNameVersion)); } @Test - public void testSetNameVersion() { + void testSetNameVersion() { defaultConfig.setNameVersion(!randomIsNameVersion); assertThat(defaultConfig.isNameVersion(), is(!randomIsNameVersion)); } @Test - public void testIsArchitectureNameVersion() { + void testIsArchitectureNameVersion() { assertThat(defaultConfig.isArchitectureNameVersion(), is(true)); assertThat(randomConfig.isArchitectureNameVersion(), is(randomIsArchitectureNameVersion)); } @Test - public void testSetArchitectureNameVersion() { + void testSetArchitectureNameVersion() { defaultConfig.setArchitectureNameVersion(!randomIsArchitectureNameVersion); assertThat(defaultConfig.isArchitectureNameVersion(), is(!randomIsArchitectureNameVersion)); } @Test - public void testIsWindowsFeatureUpdate() { + void testIsWindowsFeatureUpdate() { assertThat(defaultConfig.isWindowsFeatureUpdate(), is(true)); assertThat(randomConfig.isWindowsFeatureUpdate(), is(randomIsWindowsFeatureUpdate)); } @Test - public void testSetWindowsFeatureUpdate() { + void testSetWindowsFeatureUpdate() { defaultConfig.setWindowsFeatureUpdate(!randomIsWindowsFeatureUpdate); assertThat(defaultConfig.isWindowsFeatureUpdate(), is(!randomIsWindowsFeatureUpdate)); } @Test - public void testIsOsName() { + void testIsOsName() { assertThat(defaultConfig.isOsName(), is(true)); assertThat(randomConfig.isOsName(), is(randomIsOsName)); } @Test - public void testSetOsName() { + void testSetOsName() { defaultConfig.setOsName(!randomIsOsName); assertThat(defaultConfig.isOsName(), is(!randomIsOsName)); } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeFileTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeFileTest.java index 9ac7a981c..009403b12 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeFileTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeFileTest.java @@ -12,12 +12,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -public class LsbReleaseFakeFileTest { +class LsbReleaseFakeFileTest { @TempDir - File dataDir; + private File dataDir; - private String fakeDistributorId = "megasupercorp"; - private String fakeRelease = "1.2.3"; + private final String fakeDistributorId = "megasupercorp"; + private final String fakeRelease = "1.2.3"; private LsbRelease fakeLsbRelease; @BeforeEach diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeTest.java index 78a5efe28..7778b9679 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseFakeTest.java @@ -5,10 +5,10 @@ import org.junit.jupiter.api.Test; -public class LsbReleaseFakeTest { - private String fakeDistributorId = "megasupercorp"; - private String fakeRelease = "1.2.3"; - private LsbRelease fakeLsbRelease = new LsbRelease(fakeDistributorId, fakeRelease); +class LsbReleaseFakeTest { + private final String fakeDistributorId = "megasupercorp"; + private final String fakeRelease = "1.2.3"; + private final LsbRelease fakeLsbRelease = new LsbRelease(fakeDistributorId, fakeRelease); @Test void matchingFakeDistributorId() { diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseRealTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseRealTest.java index e3408b431..2bfc3f881 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseRealTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/LsbReleaseRealTest.java @@ -8,7 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class LsbReleaseRealTest { +class LsbReleaseRealTest { private LsbRelease lsbRelease; @BeforeEach diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/NodeLabelCacheTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/NodeLabelCacheTest.java index ce298c9db..2de20accc 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/NodeLabelCacheTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/NodeLabelCacheTest.java @@ -8,6 +8,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.FilePath; import hudson.Launcher; @@ -26,7 +27,6 @@ import hudson.util.DescribableList; import hudson.util.LogTaskListener; import hudson.util.RingBufferLogHandler; -import jakarta.servlet.ServletException; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -37,11 +37,11 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; import org.kohsuke.stapler.interceptor.RequirePOST; @@ -51,22 +51,19 @@ * * @author Mark Waite */ -public class NodeLabelCacheTest { +@WithJenkins +class NodeLabelCacheTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - - public NodeLabelCacheTest() { - /* Intentionally empty constructor */ - } + private JenkinsRule r; private Computer computer; private Set labelsBefore; private NodeLabelCache nodeLabelCache; private PlatformDetails localDetails; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp(JenkinsRule r) throws IOException { + this.r = r; computer = r.jenkins.toComputer(); labelsBefore = computer.getNode().getAssignedLabels(); assertThat(labelsBefore, is(not(empty()))); @@ -78,51 +75,52 @@ public void setUp() throws IOException { System.getProperty("os.version", PlatformDetailsTask.UNKNOWN_VALUE_STRING)); } - @After - public void tearDown() { + @AfterEach + void tearDown() { Set labelsAfter = computer.getNode().getAssignedLabels(); assertThat(labelsBefore, everyItem(in(labelsAfter))); } @Test - public void testCacheAndRefreshModel() throws Exception { + void testCacheAndRefreshModel() throws Exception { nodeLabelCache.cacheAndRefreshModel(computer, computer.getChannel()); } @Test - public void testCacheLabels() throws Exception { + void testCacheLabels() throws Exception { nodeLabelCache.cacheLabels(computer, computer.getChannel()); } @Test - public void testRefreshModel() { + void testRefreshModel() { nodeLabelCache.refreshModel(computer); } @Test - public void testRefreshModelNullComputer() { + void testRefreshModelNullComputer() { nodeLabelCache.refreshModel(null); } @Test - public void testRefreshModelNullingComputer() { + void testRefreshModelNullingComputer() { Computer nullingComputer = new NullingComputer(computer.getNode()); nodeLabelCache.refreshModel(nullingComputer); } - @Test(expected = IOException.class) - public void testCacheLabelsNullingComputer() throws Exception { + @Test + void testCacheLabelsNullingComputer() { Computer nullingComputer = new NullingComputer(computer.getNode()); - nodeLabelCache.cacheLabels(nullingComputer, nullingComputer.getChannel()); + assertThrows( + IOException.class, () -> nodeLabelCache.cacheLabels(nullingComputer, nullingComputer.getChannel())); } @Test - public void testOnConfigurationChange() { + void testOnConfigurationChange() { nodeLabelCache.onConfigurationChange(); } @Test - public void testRequestComputerPlatformDetails() throws Exception { + void testRequestComputerPlatformDetails() throws Exception { PlatformDetails platformDetails = nodeLabelCache.requestComputerPlatformDetails(computer, computer.getChannel()); assertThat(platformDetails.getArchitecture(), is(localDetails.getArchitecture())); @@ -133,7 +131,7 @@ public void testRequestComputerPlatformDetails() throws Exception { } @Test - public void testGetLabelsForNode() throws IOException { + void testGetLabelsForNode() { Collection labels = nodeLabelCache.getLabelsForNode(computer.getNode()); PlatformDetailsTask task = new PlatformDetailsTask(); for (LabelAtom labelAtom : labels) { @@ -152,30 +150,33 @@ public void testGetLabelsForNode() throws IOException { } @Test - public void testGetLabelsForNode_IsNull() throws Exception { + void testGetLabelsForNode_IsNull() { Node nullingNode = new NullingNode(); Collection labels = nodeLabelCache.getLabelsForNode(nullingNode); assertThat(labels, is(empty())); } - @Test(expected = IOException.class) - public void testRequestComputerPlatformDetails_ChannelThrows() throws Exception { + @Test + void testRequestComputerPlatformDetails_ChannelThrows() { Computer throwingComputer = new NullingComputer(computer.getNode(), new IOException("Oops")); - nodeLabelCache.requestComputerPlatformDetails(throwingComputer, throwingComputer.getChannel()); + assertThrows( + IOException.class, + () -> nodeLabelCache.requestComputerPlatformDetails(throwingComputer, throwingComputer.getChannel())); } - @Test(expected = IOException.class) - public void testRequestComputerPlatformDetails_ChannelThrowsOnNullComputer() throws Exception { - nodeLabelCache.requestComputerPlatformDetails(null, computer.getChannel()); + @Test + void testRequestComputerPlatformDetails_ChannelThrowsOnNullComputer() { + assertThrows( + IOException.class, () -> nodeLabelCache.requestComputerPlatformDetails(null, computer.getChannel())); } - @Test(expected = IOException.class) - public void testRequestComputerPlatformDetails_ChannelThrowsOnNullChannel() throws Exception { - nodeLabelCache.requestComputerPlatformDetails(computer, null); + @Test + void testRequestComputerPlatformDetails_ChannelThrowsOnNullChannel() { + assertThrows(IOException.class, () -> nodeLabelCache.requestComputerPlatformDetails(computer, null)); } @Test - public void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalException() throws Exception { + void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalException() throws Exception { // Setup a recorder for agent log RingBufferLogHandler agentLogHandler = new RingBufferLogHandler(10); Logger agentLogger = Logger.getLogger(NodeLabelCacheTest.class.getName()); @@ -190,7 +191,7 @@ public void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalException( } @Test - public void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalExceptionForNullComputer() throws Exception { + void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalExceptionForNullComputer() throws Exception { // Setup a recorder for agent log RingBufferLogHandler agentLogHandler = new RingBufferLogHandler(10); Logger agentLogger = Logger.getLogger(NodeLabelCacheTest.class.getName()); @@ -205,7 +206,7 @@ public void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalExceptionF } @Test - public void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalExceptionForComputer() throws Exception { + void testPreOnline_ChannelLogsDetailCollectionIgnoredOnInternalExceptionForComputer() throws Exception { // Setup a recorder for agent log RingBufferLogHandler agentLogHandler = new RingBufferLogHandler(10); Logger agentLogger = Logger.getLogger(NodeLabelCacheTest.class.getName()); @@ -248,13 +249,13 @@ public Charset getDefaultCharset() { } @Override - public List getLogRecords() throws IOException, InterruptedException { + public List getLogRecords() { throw new UnsupportedOperationException("Unsupported"); } @Override @RequirePOST - public void doLaunchSlaveAgent(StaplerRequest2 sr, StaplerResponse2 sr1) throws IOException, ServletException { + public void doLaunchSlaveAgent(StaplerRequest2 sr, StaplerResponse2 sr1) { throw new UnsupportedOperationException("Unsupported"); } @@ -315,13 +316,13 @@ public Charset getDefaultCharset() { } @Override - public List getLogRecords() throws IOException, InterruptedException { + public List getLogRecords() { throw new UnsupportedOperationException("Unsupported"); } @Override @RequirePOST - public void doLaunchSlaveAgent(StaplerRequest2 sr, StaplerResponse2 sr1) throws IOException, ServletException { + public void doLaunchSlaveAgent(StaplerRequest2 sr, StaplerResponse2 sr1) { throw new UnsupportedOperationException("Unsupported"); } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsCheckRolesTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsCheckRolesTest.java index 3d47e57f0..fdcf26f23 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsCheckRolesTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsCheckRolesTest.java @@ -1,37 +1,42 @@ package org.jvnet.hudson.plugins.platformlabeler; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Collection; import jenkins.security.Roles; import org.jenkinsci.remoting.Role; import org.jenkinsci.remoting.RoleChecker; import org.jenkinsci.remoting.RoleSensitive; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Check the role checker in PlatformDetailsTask. * * @author Mark Waite */ -public class PlatformDetailsCheckRolesTest { +@WithJenkins +class PlatformDetailsCheckRolesTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private PlatformDetailsTask platformDetailsTask; - @Before - public void createPlatformDetailsTask() { + @BeforeEach + void setUp(JenkinsRule r) { + this.r = r; platformDetailsTask = new PlatformDetailsTask(); } @Test - public void testCheckRoles() { + void testCheckRoles() { RoleChecker checker = new RoleChecker() { @Override - public void check(RoleSensitive rs, Collection roleCollection) throws SecurityException { + public void check(@NonNull RoleSensitive rs, @NonNull Collection roleCollection) + throws SecurityException { if (!roleCollection.contains(Roles.SLAVE)) { throw new SecurityException(Roles.SLAVE + " missing"); } @@ -40,16 +45,17 @@ public void check(RoleSensitive rs, Collection roleCollection) throws Secu platformDetailsTask.checkRoles(checker); } - @Test(expected = SecurityException.class) - public void testCheckRolesThrowsSecurityException() { + @Test + void testCheckRolesThrowsSecurityException() { RoleChecker exceptionThrowingChecker = new RoleChecker() { @Override - public void check(RoleSensitive rs, Collection roleCollection) throws SecurityException { + public void check(@NonNull RoleSensitive rs, @NonNull Collection roleCollection) + throws SecurityException { if (roleCollection.contains(Roles.SLAVE)) { throw new SecurityException(Roles.SLAVE + " found, throwing intentional exception"); } } }; - platformDetailsTask.checkRoles(exceptionThrowingChecker); + assertThrows(SecurityException.class, () -> platformDetailsTask.checkRoles(exceptionThrowingChecker)); } } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskLsbReleaseTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskLsbReleaseTest.java index 89a70b058..261253496 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskLsbReleaseTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskLsbReleaseTest.java @@ -18,14 +18,14 @@ import org.reflections.Reflections; import org.reflections.scanners.Scanners; -public class PlatformDetailsTaskLsbReleaseTest { +class PlatformDetailsTaskLsbReleaseTest { /** * Generate test parameters for Linux lsb_release-a sample files stored as resources. * * @return parameter values to be tested */ - public static Stream generateReleaseFileNames() { + static Stream generateReleaseFileNames() { String packageName = PlatformDetailsTaskLsbReleaseTest.class.getPackage().getName(); Reflections reflections = new Reflections(packageName, Scanners.Resources); diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskReleaseTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskReleaseTest.java index 813052adf..fe4c034c1 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskReleaseTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskReleaseTest.java @@ -18,7 +18,7 @@ import org.reflections.Reflections; import org.reflections.scanners.Scanners; -public class PlatformDetailsTaskReleaseTest { +class PlatformDetailsTaskReleaseTest { /** * Generate test parameters for Linux os-release, redhat-release and SuSE-release sample files @@ -26,7 +26,7 @@ public class PlatformDetailsTaskReleaseTest { * * @return parameter values to be tested */ - public static Stream generateReleaseFileNames() { + static Stream generateReleaseFileNames() { String packageName = PlatformDetailsTaskReleaseTest.class.getPackage().getName(); Reflections reflections = new Reflections(packageName, Scanners.Resources); Set fileNames = reflections.getResources(Pattern.compile(".*-release")); diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskStaticStringTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskStaticStringTest.java index e032d7002..e91f69742 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskStaticStringTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskStaticStringTest.java @@ -3,21 +3,24 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import hudson.Functions; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class PlatformDetailsTaskStaticStringTest { +class PlatformDetailsTaskStaticStringTest { /** * Generate test parameters for cases which can be tested with static string conversions. Linux @@ -26,7 +29,7 @@ public class PlatformDetailsTaskStaticStringTest { * * @return parameter values to be tested */ - public static Stream generateTestParameters() { + static Stream generateTestParameters() { Collection data = Arrays.asList(new Object[][] { /** Windows 11 */ {"Windows 11", "aarch64", "10.0"}, @@ -118,11 +121,11 @@ void testComputeLabels(String name, String arch, String version) throws Exceptio } private static String computeExpectedArch(String name, String arch) { - if (!isWindows() || !name.startsWith("Windows")) { + if (!Functions.isWindows() || !name.startsWith("Windows")) { // Trust the passed value for non-Windows systems return arch; } - if (arch != "amd64" && arch != "x86") { + if (!Objects.equals(arch, "amd64") && !Objects.equals(arch, "x86")) { // Trust the passed value for non-Intel architectures return arch; } @@ -134,7 +137,7 @@ private static String computeExpectedArch(String name, String arch) { return arch; } - private String computeExpectedName(String name) { + private static String computeExpectedName(String name) { if (name.startsWith("Windows")) { return "windows"; } @@ -145,7 +148,7 @@ private String computeExpectedName(String name) { return name.toLowerCase(Locale.ENGLISH); } - private String computeExpectedOsName(String name) { + private static String computeExpectedOsName(String name) { if (name.startsWith("Windows Server")) { if (name.contains("2022")) { return "WindowsServer2022"; @@ -162,7 +165,7 @@ private String computeExpectedOsName(String name) { return name; } - private String computeVersion(String name, String version) { + private static String computeVersion(String name, String version) { if (name.startsWith("Windows")) { switch (version) { case "4.0": @@ -186,7 +189,7 @@ private String computeVersion(String name, String version) { return version; } - private String getFreeBsdVersion(String version) { + private static String getFreeBsdVersion(String version) { /* If no freebsd-version command, return the provided default value */ File freebsdVersionCommand = new File("/bin/freebsd-version"); if (!freebsdVersionCommand.exists()) { @@ -196,7 +199,8 @@ private String getFreeBsdVersion(String version) { try { Process p = Runtime.getRuntime().exec("/bin/freebsd-version -u"); p.waitFor(); - try (BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"))) { + try (BufferedReader b = + new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) { String line = b.readLine(); if (line != null) { version = line; @@ -207,8 +211,4 @@ private String getFreeBsdVersion(String version) { } return version; } - - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskTest.java index 3de2b13ce..9c5c718cf 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskTest.java @@ -5,6 +5,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; +import hudson.Functions; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -20,7 +21,7 @@ import org.junit.jupiter.api.parallel.ExecutionMode; @Execution(ExecutionMode.CONCURRENT) -public class PlatformDetailsTaskTest { +class PlatformDetailsTaskTest { private PlatformDetailsTask platformDetailsTask; @@ -43,7 +44,7 @@ void createPlatformDetailsTask() { @DisplayName("test remote call for platform details") void testCall() throws Exception { PlatformDetails details = platformDetailsTask.call(); - if (isWindows()) { + if (Functions.isWindows()) { assertThat(details.getName(), is("windows")); } else { assertThat(details.getName(), is(not("windows"))); @@ -124,7 +125,7 @@ void testCanonicalLinuxArchStreamEmpty() throws IOException { @Test @DisplayName("test Linux label computation without lsb_release") void testComputeLabelsLinuxWithoutLsbRelease() throws Exception { - if (isWindows() || !Files.exists(Path.of("/etc/os-release"))) { + if (Functions.isWindows() || !Files.exists(Path.of("/etc/os-release"))) { return; } String unknown = PlatformDetailsTask.UNKNOWN_VALUE_STRING; @@ -136,7 +137,7 @@ void testComputeLabelsLinuxWithoutLsbRelease() throws Exception { @Test @DisplayName("test Linux label computation with null lsb_release") void testComputeLabelsLinuxWithNullLsbRelease() throws Exception { - if (isWindows() || !Files.exists(Path.of("/etc/os-release"))) { + if (Functions.isWindows() || !Files.exists(Path.of("/etc/os-release"))) { return; } LsbRelease release = null; @@ -175,7 +176,7 @@ void testCheckWindows32BitAMD64SecondArgument() { @Test @DisplayName("test operating system name") void compareOSName() throws Exception { - if (isWindows() || !Files.exists(Path.of("/etc/os-release"))) { + if (Functions.isWindows() || !Files.exists(Path.of("/etc/os-release"))) { return; } String computedName = platformDetailsTask @@ -196,7 +197,7 @@ void getReleaseIdentifierMissingFileReturnsUnknownValue() throws Exception { @Test @DisplayName("Read Debian version identifier missing file") - void getDebianVersionIdentifierMissingFileReturnsUnknownValue() throws Exception { + void getDebianVersionIdentifierMissingFileReturnsUnknownValue() { platformDetailsTask.setDebianVersion(new File("/this/file/does/not/exist")); String version = platformDetailsTask.getDebianVersionIdentifier(); assertThat(version, is(PlatformDetailsTask.UNKNOWN_VALUE_STRING)); @@ -204,7 +205,7 @@ void getDebianVersionIdentifierMissingFileReturnsUnknownValue() throws Exception @Test @DisplayName("Read Debian version identifier null file") - void getDebianVersionNullFileReturnsUnknownValue() throws Exception { + void getDebianVersionNullFileReturnsUnknownValue() { platformDetailsTask.setDebianVersion(null); String version = platformDetailsTask.getDebianVersionIdentifier(); assertThat(version, is(PlatformDetailsTask.UNKNOWN_VALUE_STRING)); @@ -239,7 +240,7 @@ void getRedhatReleaseIdentifierWrongFileReturnsUnknownValue() throws Exception { @Test @DisplayName("Read SUSE release identifier missing file") - void getSuseReleaseIdentifierMissingFileReturnsUnknownValue() throws Exception { + void getSuseReleaseIdentifierMissingFileReturnsUnknownValue() { platformDetailsTask.setSuseRelease(new File("/this/file/does/not/exist")); String name = platformDetailsTask.getSuseReleaseIdentifier("ID"); assertThat(name, is(PlatformDetailsTask.UNKNOWN_VALUE_STRING)); @@ -247,7 +248,7 @@ void getSuseReleaseIdentifierMissingFileReturnsUnknownValue() throws Exception { @Test @DisplayName("Read SUSE release identifier null file") - void getSuseReleaseIdentifierNullFileReturnsUnknownValue() throws Exception { + void getSuseReleaseIdentifierNullFileReturnsUnknownValue() { platformDetailsTask.setSuseRelease(null); String name = platformDetailsTask.getSuseReleaseIdentifier("ID"); assertThat(name, is(PlatformDetailsTask.UNKNOWN_VALUE_STRING)); @@ -255,8 +256,8 @@ void getSuseReleaseIdentifierNullFileReturnsUnknownValue() throws Exception { @Test @DisplayName("Read SUSE release identifier wrong file") - void getSuseReleaseIdentifierWrongFileReturnsUnknownValue() throws Exception { - if (isWindows() || !Files.exists(Path.of("/etc/os-release"))) { + void getSuseReleaseIdentifierWrongFileReturnsUnknownValue() { + if (Functions.isWindows() || !Files.exists(Path.of("/etc/os-release"))) { return; } platformDetailsTask.setSuseRelease(new File("/etc/hosts")); // Not SuSE-release file @@ -267,7 +268,7 @@ void getSuseReleaseIdentifierWrongFileReturnsUnknownValue() throws Exception { @Test @DisplayName("Compare operating system version") void compareOSVersion() throws Exception { - if (isWindows() || !Files.exists(Path.of("/etc/os-release"))) { + if (Functions.isWindows() || !Files.exists(Path.of("/etc/os-release"))) { return; } PlatformDetails details = platformDetailsTask.computeLabels(SPECIAL_CASE_ARCH, "linux", "xyzzy"); @@ -301,8 +302,4 @@ void compareOSVersion() throws Exception { assertThat(details.getVersion(), anyOf(is(version), is(foundValue))); } } - - private boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskWindowsReleaseTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskWindowsReleaseTest.java index 705c87ee2..060e2948d 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskWindowsReleaseTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTaskWindowsReleaseTest.java @@ -17,14 +17,14 @@ import org.reflections.Reflections; import org.reflections.scanners.Scanners; -public class PlatformDetailsTaskWindowsReleaseTest { +class PlatformDetailsTaskWindowsReleaseTest { /** * Generate test parameters for Windows feature updates using sample files stored as resources. * * @return parameter values to be tested */ - public static Stream generateWindowsReleaseFileNames() { + static Stream generateWindowsReleaseFileNames() { String packageName = PlatformDetailsTaskWindowsReleaseTest.class.getPackage().getName(); Reflections reflections = new Reflections(packageName, Scanners.Resources); diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTest.java index d1c33922c..fb597036a 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformDetailsTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class PlatformDetailsTest { +class PlatformDetailsTest { private String name; private String arch; @@ -40,8 +40,6 @@ public class PlatformDetailsTest { private String osName; private PlatformDetails details; - public PlatformDetailsTest() {} - @BeforeEach void randomizeData() { name = randomName(); @@ -151,13 +149,13 @@ void testDetailsWithoutOsName() { assertThat(detailsWithoutOsName.getOsName(), is(nullValue())); } - private final Random random = new Random(); + private static final Random random = new Random(); - private final String[] names = { + private static final String[] names = { "Windows 10", "alpine", "centos", "debian", "fedora", "freebsd", "macos", "raspbian", "ubuntu" }; - private final String[] versions = { + private static final String[] versions = { "3.17.9", "3.18.12", "3.19.7", @@ -186,23 +184,23 @@ void testDetailsWithoutOsName() { "40", }; - private final String[] windowsFeatureUpdates = { + private static final String[] windowsFeatureUpdates = { "1703", "1709", "1803", "1809", "1903", "1909", "2003", "2009", "2103", "2109", "2203" }; - private String randomName() { + private static String randomName() { return names[random.nextInt(names.length)]; } - private String randomArch() { + private static String randomArch() { return "amd64"; } - private String randomVersion() { + private static String randomVersion() { return versions[random.nextInt(versions.length)]; } - private String randomWindowsFeatureUpdate() { + private static String randomWindowsFeatureUpdate() { return windowsFeatureUpdates[random.nextInt(windowsFeatureUpdates.length)]; } } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformLabelerTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformLabelerTest.java index bf64ab926..70c2da887 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformLabelerTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/PlatformLabelerTest.java @@ -30,20 +30,18 @@ import hudson.model.labels.LabelAtom; import java.util.Collection; import java.util.HashSet; -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 robertc */ -public class PlatformLabelerTest { - - @Rule - public final JenkinsRule j = new JenkinsRule(); +@WithJenkins +class PlatformLabelerTest { @Test - public void testLookupCached() { + void testLookupCached(JenkinsRule j) { Collection expected = new HashSet<>(); expected.add(j.jenkins.getLabelAtom("foo")); expected.add(j.jenkins.getLabelAtom("bar")); @@ -53,11 +51,9 @@ public void testLookupCached() { } @Test - public void testLookupUncached() throws Exception { + void testLookupUncached(JenkinsRule j) { /* remove the Jenkins node from the cache */ - if (NodeLabelCache.nodeLabels.containsKey(j.jenkins)) { - NodeLabelCache.nodeLabels.remove(j.jenkins); - } + NodeLabelCache.nodeLabels.remove(j.jenkins); Collection labels = new PlatformLabeler().findLabels(j.jenkins); assertThat(labels, is(empty())); } diff --git a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/WindowsReleaseTest.java b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/WindowsReleaseTest.java index f100c5865..490b0637d 100644 --- a/src/test/java/org/jvnet/hudson/plugins/platformlabeler/WindowsReleaseTest.java +++ b/src/test/java/org/jvnet/hudson/plugins/platformlabeler/WindowsReleaseTest.java @@ -27,16 +27,19 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.matchesPattern; +import hudson.Functions; import java.io.File; import java.net.URL; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class WindowsReleaseTest { +class WindowsReleaseTest { private final WindowsRelease windowsRelease = new WindowsRelease(); - private final WindowsRelease windowsReleaseFile; + private WindowsRelease windowsReleaseFile; - public WindowsReleaseTest() throws Exception { + @BeforeEach + void setUp() throws Exception { URL resource = getClass().getResource("windows/10.0.1903/reg-query"); File dataFile = new File(resource.toURI()); windowsReleaseFile = new WindowsRelease(dataFile); @@ -49,7 +52,7 @@ void testReleaseFromFile() { @Test void testRelease() { - if (isWindows()) { + if (Functions.isWindows()) { assertThat(windowsRelease.release(), matchesPattern("[12][0-9][0-9][0-9]")); } else { String expected = PlatformDetailsTask.UNKNOWN_WINDOWS_VALUE_STRING; @@ -66,8 +69,4 @@ void testDistributorId() { void testDistributorIdFromFile() { assertThat(windowsReleaseFile.distributorId(), is("Microsoft")); } - - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } }