diff --git a/pom.xml b/pom.xml index 64571015..975041ac 100644 --- a/pom.xml +++ b/pom.xml @@ -21,6 +21,7 @@ UTF-8 Max + false diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipActionTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipActionTest.java index 8cafd7ac..89a73ea0 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipActionTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipActionTest.java @@ -27,27 +27,35 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import hudson.model.FreeStyleProject; import hudson.model.User; import hudson.tasks.Mailer; -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.JenkinsRule.WebClient; import org.htmlunit.html.HtmlPage; import com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerHelper; import com.synopsys.arc.jenkins.plugins.ownership.nodes.NodeOwnerHelper; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class OwnershipActionTest { +@WithJenkins +class OwnershipActionTest { - @Rule public JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } @Test - public void test() throws Exception { + void test() throws Exception { // There is no particular reason why email value should look like this, but for a user configurable field this is a realistic scenario. String mail = "\"T&J\" "; String id = "_T&J_"; @@ -64,7 +72,7 @@ public void test() throws Exception { assertThat(job.asXml(), not(containsString(""))); // Find anchor by partial href match - HtmlUnit normalizes URLs automatically // Try with URL-encoded version first (as it appears in HTML) - String encodedId = java.net.URLEncoder.encode(id, "UTF-8"); + String encodedId = java.net.URLEncoder.encode(id, StandardCharsets.UTF_8); String userUrlEncoded = j.getURL() + "user/" + encodedId; String userUrlPlain = j.getURL() + "user/" + id; diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipDescriptionTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipDescriptionTest.java index f36dcb3f..c43a4329 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipDescriptionTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/OwnershipDescriptionTest.java @@ -7,21 +7,23 @@ import java.util.Collections; import jenkins.model.IdStrategy; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; + +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 OwnershipDescriptionTest { +@WithJenkins +class OwnershipDescriptionTest { private static final IdStrategy CASE_SENSITIVE = new IdStrategy.CaseSensitive(); - @Rule - public final JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + j = rule; applyIdStrategy(CASE_SENSITIVE); } @@ -42,13 +44,13 @@ public IdStrategy getGroupIdStrategy() { } @Test - public void isOwnerShouldRespectCaseSensitiveIdStrategy() throws Exception { + void isOwnerShouldRespectCaseSensitiveIdStrategy() { User user = User.get("owner"); - OwnershipDescription description = new OwnershipDescription(true, "owner", Collections.emptyList()); + OwnershipDescription description = new OwnershipDescription(true, "owner", Collections.emptyList()); assertThat("OwnershipDescription doesn't respect case sensitive strategy", description.isOwner(user, false), equalTo(true)); - description = new OwnershipDescription(true, "OWNER", Collections.emptyList()); + description = new OwnershipDescription(true, "OWNER", Collections.emptyList()); assertThat("OwnershipDescription doesn't respect case sensitive strategy", description.isOwner(user, false), equalTo(false)); description = new OwnershipDescription(true, "another.owner", Arrays.asList("owner")); @@ -59,14 +61,14 @@ public void isOwnerShouldRespectCaseSensitiveIdStrategy() throws Exception { } @Test - public void isOwnerShouldRespectCaseInsensitiveIdStrategy() throws Exception { + void isOwnerShouldRespectCaseInsensitiveIdStrategy() throws Exception { applyIdStrategy(IdStrategy.CASE_INSENSITIVE); User user = User.get("owner"); - OwnershipDescription description = new OwnershipDescription(true, "owner", Collections.emptyList()); + OwnershipDescription description = new OwnershipDescription(true, "owner", Collections.emptyList()); assertThat("OwnershipDescription doesn't respect case sensitive strategy", description.isOwner(user, false), equalTo(true)); - description = new OwnershipDescription(true, "OWNER", Collections.emptyList()); + description = new OwnershipDescription(true, "OWNER", Collections.emptyList()); assertThat("OwnershipDescription doesn't respect case sensitive strategy", description.isOwner(user, false), equalTo(true)); description = new OwnershipDescription(true, "another.owner", Arrays.asList("owner")); diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerHelperTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerHelperTest.java index 7afb8b22..60e9f1dd 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerHelperTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerHelperTest.java @@ -25,25 +25,32 @@ import hudson.model.FreeStyleProject; import org.jenkinsci.plugins.ownership.model.OwnershipHelperLocator; -import static org.junit.Assert.assertEquals; -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; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link JobOwnerHelper}. * @author Oleg Nenashev */ -public class JobOwnerHelperTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class JobOwnerHelperTest { + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } + @Test - public void locatorShouldReturnRightHelperForFolder() throws Exception { + void locatorShouldReturnRightHelperForFolder() throws Exception { FreeStyleProject folder = j.jenkins.createProject(FreeStyleProject.class, "myFolder"); - - assertEquals("OwnershipHelperLocator should return the FolderOwnershipHelper instance", - OwnershipHelperLocator.locate(folder), JobOwnerHelper.Instance); + + assertEquals( + JobOwnerHelper.Instance, OwnershipHelperLocator.locate(folder), "OwnershipHelperLocator should return the FolderOwnershipHelper instance"); } } diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobActionSecurityTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobActionSecurityTest.java index 0fcb8fc2..ad09fd25 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobActionSecurityTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobActionSecurityTest.java @@ -27,8 +27,6 @@ import org.htmlunit.FailingHttpStatusCodeException; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; -import org.htmlunit.html.HtmlForm; -import org.htmlunit.html.HtmlPage; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipPlugin; import hudson.model.FreeStyleProject; @@ -36,32 +34,33 @@ import hudson.model.User; import jenkins.model.Jenkins; import net.sf.json.JSONObject; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; /** * Security tests for JobOwnerJobAction endpoints. * Tests CSRF protection and permission checks for SECURITY-2062 fixes. */ -public class JobOwnerJobActionSecurityTest { +@WithJenkins +class JobOwnerJobActionSecurityTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private FreeStyleProject project; - @Before - public void setupSecurity() throws Exception { + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception{ + r = rule; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); // Create users explicitly @@ -109,7 +108,7 @@ public void setupSecurity() throws Exception { @Test @Issue("SECURITY-2062") - public void doOwnersSubmit_requiresPOST() throws Exception { + void doOwnersSubmit_requiresPOST() throws Exception { WebClient wc = r.createWebClient(); wc.login("admin", "admin"); @@ -128,7 +127,7 @@ public void doOwnersSubmit_requiresPOST() throws Exception { @Test @Issue("SECURITY-2062") - public void doOwnersSubmit_requiresManageOwnershipPermission() throws Exception { + void doOwnersSubmit_requiresManageOwnershipPermission() throws Exception { WebClient wc = r.createWebClient(); // Try with readonly user - should fail @@ -153,7 +152,7 @@ public void doOwnersSubmit_requiresManageOwnershipPermission() throws Exception @Test @Issue("SECURITY-2062") - public void doOwnersSubmit_allowsPOSTWithProperPermissions() throws Exception { + void doOwnersSubmit_allowsPOSTWithProperPermissions() throws Exception { WebClient wc = r.createWebClient(); wc.login("admin", "admin"); @@ -169,7 +168,7 @@ public void doOwnersSubmit_allowsPOSTWithProperPermissions() throws Exception { wc.createCrumbedUrl(project.getUrl() + "ownership/ownersSubmit"), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded"); - req.setRequestBody("json=" + formData.toString()); + req.setRequestBody("json=" + formData); wc.getPage(req); // Verify ownership was changed @@ -178,7 +177,7 @@ public void doOwnersSubmit_allowsPOSTWithProperPermissions() throws Exception { @Test @Issue("SECURITY-2062") - public void doProjectSpecificSecuritySubmit_requiresPOST() throws Exception { + void doProjectSpecificSecuritySubmit_requiresPOST() throws Exception { WebClient wc = r.createWebClient(); wc.login("admin", "admin"); @@ -197,7 +196,7 @@ public void doProjectSpecificSecuritySubmit_requiresPOST() throws Exception { @Test @Issue("SECURITY-2062") - public void doProjectSpecificSecuritySubmit_requiresManageOwnershipPermission() throws Exception { + void doProjectSpecificSecuritySubmit_requiresManageOwnershipPermission() throws Exception { WebClient wc = r.createWebClient(); // Try with readonly user - should fail @@ -219,7 +218,7 @@ public void doProjectSpecificSecuritySubmit_requiresManageOwnershipPermission() @Test @Issue("SECURITY-2062") - public void doRestoreDefaultSpecificSecuritySubmit_requiresPOST() throws Exception { + void doRestoreDefaultSpecificSecuritySubmit_requiresPOST() throws Exception { WebClient wc = r.createWebClient(); wc.login("admin", "admin"); @@ -238,7 +237,7 @@ public void doRestoreDefaultSpecificSecuritySubmit_requiresPOST() throws Excepti @Test @Issue("SECURITY-2062") - public void doRestoreDefaultSpecificSecuritySubmit_requiresManageOwnershipPermission() throws Exception { + void doRestoreDefaultSpecificSecuritySubmit_requiresManageOwnershipPermission() throws Exception { WebClient wc = r.createWebClient(); // Try with readonly user - should fail @@ -260,7 +259,7 @@ public void doRestoreDefaultSpecificSecuritySubmit_requiresManageOwnershipPermis @Test @Issue("SECURITY-2062") - public void configureUser_cannotModifyOwnership() throws Exception { + void configureUser_cannotModifyOwnership() throws Exception { WebClient wc = r.createWebClient(); // User with CONFIGURE but not MANAGE_ITEMS_OWNERSHIP should not be able to modify ownership diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobPropertyTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobPropertyTest.java index e978957d..3fdd5347 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobPropertyTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/jobs/JobOwnerJobPropertyTest.java @@ -37,28 +37,29 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import jenkins.model.Jenkins; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static hudson.cli.CLICommandInvoker.Matcher.failedWith; import static hudson.cli.CLICommandInvoker.Matcher.succeededSilently; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -public class JobOwnerJobPropertyTest { +@WithJenkins +class JobOwnerJobPropertyTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Before - public void setupSecurity() { + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); MockAuthorizationStrategy mas = new MockAuthorizationStrategy(); mas.grant(Jenkins.ADMINISTER) // Implies MANAGE_ITEMS_OWNERSHIP. @@ -72,7 +73,7 @@ public void setupSecurity() { @Test @Issue("SECURITY-498") - public void changeOwnerViaPost() throws Exception { + void changeOwnerViaPost() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); p.getProperty(JobOwnerJobProperty.class).setOwnershipDescription(new OwnershipDescription(true, "admin", null)); @@ -103,7 +104,7 @@ public void changeOwnerViaPost() throws Exception { @Test @Issue("SECURITY-498") - public void changeOwnerViaCLI() throws Exception { + void changeOwnerViaCLI() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); p.getProperty(JobOwnerJobProperty.class).setOwnershipDescription(new OwnershipDescription(true, "admin", null)); diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/OwnerNodePropertyTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/OwnerNodePropertyTest.java index 51f40f9f..0cfbcc02 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/OwnerNodePropertyTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/OwnerNodePropertyTest.java @@ -35,27 +35,28 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import jenkins.model.Jenkins; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static hudson.cli.CLICommandInvoker.Matcher.failedWith; import static hudson.cli.CLICommandInvoker.Matcher.succeededSilently; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -public class OwnerNodePropertyTest { +@WithJenkins +class OwnerNodePropertyTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Before - public void setupSecurity() { + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); MockAuthorizationStrategy mas = new MockAuthorizationStrategy(); mas.grant(Jenkins.ADMINISTER) // Implies MANAGE_SLAVES_OWNERSHIP. @@ -69,7 +70,7 @@ public void setupSecurity() { @Test @Issue("SECURITY-498") - public void changeOwnerViaPost() throws Exception { + void changeOwnerViaPost() throws Exception { String nodeName; // Computer#updateByXml replaces the existing node with a new instance, so we always need to look up the current instance. String nodeUrl; { @@ -106,7 +107,7 @@ public void changeOwnerViaPost() throws Exception { @Test @Issue("SECURITY-498") - public void changeOwnerViaCLI() throws Exception { + void changeOwnerViaCLI() throws Exception { String nodeName; { Node n = r.createSlave(); diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/security/rolestrategy/AbstractOwnershipRoleMacroTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/security/rolestrategy/AbstractOwnershipRoleMacroTest.java index c8c75e30..2a990327 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/security/rolestrategy/AbstractOwnershipRoleMacroTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/security/rolestrategy/AbstractOwnershipRoleMacroTest.java @@ -29,9 +29,10 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.security.Permission; -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; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -39,16 +40,21 @@ /** * Tests for {@link AbstractOwnershipRoleMacro} focusing on null and empty SID validation. */ -public class AbstractOwnershipRoleMacroTest { - - @Rule - public final JenkinsRule j = new JenkinsRule(); +@WithJenkins +class AbstractOwnershipRoleMacroTest { + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } + /** * Test that hasPermission returns false when PermissionEntry is null. */ @Test - public void testHasPermissionWithNullEntry() throws Exception { + void testHasPermissionWithNullEntry() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -59,12 +65,12 @@ public void testHasPermissionWithNullEntry() throws Exception { assertThat("Access should be denied when PermissionEntry is null", result, equalTo(false)); } - + /** * Test that hasPermission returns false when PermissionEntry.getSid() returns null. */ @Test - public void testHasPermissionWithNullSid() throws Exception { + void testHasPermissionWithNullSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -77,12 +83,12 @@ public void testHasPermissionWithNullSid() throws Exception { assertThat("Access should be denied when SID is null", result, equalTo(false)); } - + /** * Test that hasPermission returns false when PermissionEntry.getSid() returns empty string. */ @Test - public void testHasPermissionWithEmptySid() throws Exception { + void testHasPermissionWithEmptySid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -95,12 +101,12 @@ public void testHasPermissionWithEmptySid() throws Exception { assertThat("Access should be denied when SID is empty", result, equalTo(false)); } - + /** * Test that hasPermission returns false when PermissionEntry.getSid() returns whitespace-only string. */ @Test - public void testHasPermissionWithWhitespaceSid() throws Exception { + void testHasPermissionWithWhitespaceSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -113,12 +119,12 @@ public void testHasPermissionWithWhitespaceSid() throws Exception { assertThat("Access should be denied when SID contains only whitespace", result, equalTo(false)); } - + /** * Test that hasPermission(String sid, ...) returns false when sid is null. */ @Test - public void testHasPermissionWithNullStringSid() throws Exception { + void testHasPermissionWithNullStringSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -129,12 +135,12 @@ public void testHasPermissionWithNullStringSid() throws Exception { assertThat("Access should be denied when SID string is null", result, equalTo(false)); } - + /** * Test that hasPermission(String sid, ...) returns false when sid is empty string. */ @Test - public void testHasPermissionWithEmptyStringSid() throws Exception { + void testHasPermissionWithEmptyStringSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -145,12 +151,12 @@ public void testHasPermissionWithEmptyStringSid() throws Exception { assertThat("Access should be denied when SID string is empty", result, equalTo(false)); } - + /** * Test that hasPermission(String sid, ...) returns false when sid is whitespace-only string. */ @Test - public void testHasPermissionWithWhitespaceStringSid() throws Exception { + void testHasPermissionWithWhitespaceStringSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; @@ -161,13 +167,13 @@ public void testHasPermissionWithWhitespaceStringSid() throws Exception { assertThat("Access should be denied when SID string contains only whitespace", result, equalTo(false)); } - + /** * Test that hasPermission works correctly with valid SID (even if user doesn't exist). * This test verifies that null/empty checks don't interfere with normal operation. */ @Test - public void testHasPermissionWithValidSid() throws Exception { + void testHasPermissionWithValidSid() throws Exception { OwnerRoleMacro macro = new OwnerRoleMacro(); FreeStyleProject project = j.createFreeStyleProject("test"); Permission permission = Item.READ; diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/util/mail/MailFormatterTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/util/mail/MailFormatterTest.java index d86c4f30..6700d995 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/util/mail/MailFormatterTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/util/mail/MailFormatterTest.java @@ -25,27 +25,32 @@ package com.synopsys.arc.jenkins.plugins.ownership.util.mail; import org.jenkinsci.plugins.ownership.util.mail.MailFormatter; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; -import static org.junit.Assert.*; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link MailFormatter}. * @author Oleg Nenashev */ -public class MailFormatterTest { +@WithJenkins +class MailFormatterTest { - MailFormatter formatter = new MailFormatter(); + private final MailFormatter formatter = new MailFormatter(); /** * Just checks if nothing breaks horribly. * @throws UnsupportedEncodingException Issues with the default encoding * @throws MalformedURLException {@link MailFormatter} generated wrong link */ - public @Test void spotCheck() throws UnsupportedEncodingException, MalformedURLException { + @Test + void spotCheck() throws UnsupportedEncodingException, MalformedURLException { String res = formatter.createMailToString( Arrays.asList("test@foo.bar"), Arrays.asList("test1@foo.bar", "test2@foo.bar"), null, diff --git a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/wrappers/OwnershipBuildWrapperTest.java b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/wrappers/OwnershipBuildWrapperTest.java index 6eadf7db..a6a1c3a5 100644 --- a/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/wrappers/OwnershipBuildWrapperTest.java +++ b/src/test/java/com/synopsys/arc/jenkins/plugins/ownership/wrappers/OwnershipBuildWrapperTest.java @@ -26,8 +26,6 @@ import com.cloudbees.hudson.plugins.folder.Folder; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; -import com.synopsys.arc.jenkins.plugins.ownership.OwnershipPlugin; -import com.synopsys.arc.jenkins.plugins.ownership.OwnershipPluginConfiguration; import com.synopsys.arc.jenkins.plugins.ownership.extensions.item_ownership_policy.AssignCreatorPolicy; import com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerHelper; import com.synopsys.arc.jenkins.plugins.ownership.nodes.NodeOwnerHelper; @@ -42,6 +40,7 @@ import hudson.model.User; import hudson.scm.NullSCM; import hudson.scm.SCMRevisionState; +import hudson.tasks.BatchFile; import hudson.tasks.Shell; import java.io.File; import java.io.IOException; @@ -51,31 +50,36 @@ import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; import org.jenkinsci.plugins.ownership.util.environment.EnvSetupOptions; import org.jenkinsci.plugins.ownership.util.mail.MailOptions; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.Rule; -import org.junit.Test; + +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +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; /** * Tests for {@link OwnershipBuildWrapper}. * @author Oleg Nenashev */ -public class OwnershipBuildWrapperTest { - - public @Rule JenkinsRule r = new JenkinsRule(); +@WithJenkins +class OwnershipBuildWrapperTest { + + private JenkinsRule r; private Slave node; private FreeStyleProject project; private User nodeOwner; private User projectOwner; - - private final static String NODE_OWNER_ID = "test_node_owner"; - private final static String PROJECT_OWNER_ID = "test_project_owner"; - - // @Before does not work due to classloader issues (?) - // See https://groups.google.com/forum/#!topic/jenkinsci-dev/3pHRVFai7T4 - public void initJenkinsInstance() throws Exception { + + private static final String NODE_OWNER_ID = "test_node_owner"; + private static final String PROJECT_OWNER_ID = "test_project_owner"; + + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + r = rule; // Create test user nodeOwner = User.get(NODE_OWNER_ID); nodeOwner.setFullName("Test Node Owner"); @@ -89,76 +93,75 @@ public void initJenkinsInstance() throws Exception { // Create node with ownership node = r.createOnlineSlave(); - NodeOwnerHelper.setOwnership(node, new OwnershipDescription(true, NODE_OWNER_ID, Collections.emptyList())); + NodeOwnerHelper.setOwnership(node, new OwnershipDescription(true, NODE_OWNER_ID, Collections.emptyList())); // Create project project = r.createFreeStyleProject(); - JobOwnerHelper.setOwnership(project, new OwnershipDescription(true, PROJECT_OWNER_ID, Collections.emptyList())); - project.getBuildersList().add(new Shell("env")); + JobOwnerHelper.setOwnership(project, new OwnershipDescription(true, PROJECT_OWNER_ID, Collections.emptyList())); + project.getBuildersList().add(isWindows() ? new BatchFile("set") : new Shell("env")); } - public @Test void testVarsPresenseOnSuccess() throws Exception { - initJenkinsInstance(); + @Test + void testVarsPresenceOnSuccess() throws Exception { final OwnershipBuildWrapper wrapper = new OwnershipBuildWrapper(true, true); project.getBuildWrappersList().add(wrapper); - testVarsPresense(false); + testVarsPresence(false); } @Issue("JENKINS-23926") - public @Test void testVarsPresenseOnSCMFailure() throws Exception { - initJenkinsInstance(); + @Test + void testVarsPresenceOnSCMFailure() throws Exception { final OwnershipBuildWrapper wrapper = new OwnershipBuildWrapper(true, true); project.getBuildWrappersList().add(wrapper); - testVarsPresense(true); + testVarsPresence(true); } @Issue("JENKINS-23947") - public @Test void testVarsPresenseOnGlobalOptions() throws Exception { - initJenkinsInstance(); + @Test + void testVarsPresenceOnGlobalOptions() throws Exception { OwnershipPluginConfigurer.forJenkinsRule(r) .withItemOwnershipPolicy(new AssignCreatorPolicy()) .withMailOptions(MailOptions.DEFAULT) .withGlobalEnvSetupOptions(new EnvSetupOptions(true, true)) .configure(); - testVarsPresense(true); + testVarsPresence(true); } @Issue("JENKINS-27715") - public @Test void testCoOwnersVarsInjection() throws Exception { - initJenkinsInstance(); + @Test + void testCoOwnersVarsInjection() throws Exception { OwnershipPluginConfigurer.forJenkinsRule(r) .withItemOwnershipPolicy(new AssignCreatorPolicy()) .withMailOptions(MailOptions.DEFAULT) .withGlobalEnvSetupOptions(new EnvSetupOptions(true, true)) .configure(); - FreeStyleBuild build = testVarsPresense(false); - r.assertLogContains("NODE_COOWNERS="+NODE_OWNER_ID, build); - r.assertLogContains("JOB_COOWNERS="+PROJECT_OWNER_ID, build); + FreeStyleBuild build = testVarsPresence(false); + r.assertLogContains("NODE_COOWNERS=" + NODE_OWNER_ID, build); + r.assertLogContains("JOB_COOWNERS=" + PROJECT_OWNER_ID, build); } - + @Test @Issue("JENKINS-28881") - public void shouldInjectInheritedOwnershipInfo() throws Exception { - initJenkinsInstance(); + void shouldInjectInheritedOwnershipInfo() throws Exception { OwnershipPluginConfigurer.forJenkinsRule(r) .withGlobalEnvSetupOptions(new EnvSetupOptions(true, true)) .configure(); // Init folder with a nested job Folder folder = r.jenkins.createProject(Folder.class, "folder"); - FolderOwnershipHelper.setOwnership(folder, new OwnershipDescription(true, PROJECT_OWNER_ID, Collections.emptyList())); + FolderOwnershipHelper.setOwnership(folder, new OwnershipDescription(true, PROJECT_OWNER_ID, Collections.emptyList())); FreeStyleProject prj = folder.createProject(FreeStyleProject.class, "projectInsideFolder"); - prj.getBuildersList().add(new Shell("env")); + prj.getBuildersList().add(isWindows() ? new BatchFile("set") : new Shell("env")); // Run test. We expect Ownership info to be inherited for the project - FreeStyleBuild build = testVarsPresense(false); - r.assertLogContains("NODE_COOWNERS="+NODE_OWNER_ID, build); - r.assertLogContains("JOB_COOWNERS="+PROJECT_OWNER_ID, build); + FreeStyleBuild build = testVarsPresence(false); + r.assertLogContains("NODE_COOWNERS=" + NODE_OWNER_ID, build); + r.assertLogContains("JOB_COOWNERS=" + PROJECT_OWNER_ID, build); } - private FreeStyleBuild testVarsPresense(boolean failSCM) throws Exception { + private FreeStyleBuild testVarsPresence(boolean failSCM) throws Exception { project.setAssignedNode(node); if (failSCM) { project.setScm(new AlwaysFailNullSCM()); @@ -172,8 +175,8 @@ private FreeStyleBuild testVarsPresense(boolean failSCM) throws Exception { // Check the build environment final EnvVars env = build.getEnvironment(TaskListener.NULL); if (!failSCM) { - r.assertLogContains("NODE_OWNER="+NODE_OWNER_ID, build); - r.assertLogContains("JOB_OWNER="+PROJECT_OWNER_ID, build); + r.assertLogContains("NODE_OWNER=" + NODE_OWNER_ID, build); + r.assertLogContains("JOB_OWNER=" + PROJECT_OWNER_ID, build); } assertTrue(env.containsKey("NODE_OWNER")); assertTrue(env.containsKey("JOB_OWNER")); diff --git a/src/test/java/org/jenkinsci/plugins/ownership/folders/FolderOwnershipPropertyTest.java b/src/test/java/org/jenkinsci/plugins/ownership/folders/FolderOwnershipPropertyTest.java index 9c049c57..945fafc5 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/folders/FolderOwnershipPropertyTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/folders/FolderOwnershipPropertyTest.java @@ -37,14 +37,14 @@ import org.jenkinsci.plugins.ownership.model.OwnershipHelperLocator; import org.jenkinsci.plugins.ownership.model.folders.FolderOwnershipHelper; import org.jenkinsci.plugins.ownership.model.folders.FolderOwnershipProperty; -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.For; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -54,20 +54,20 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; // TODO: DRY, merge with JobOwnerJobHelper once helper#setOwnership() is a non-static method @For(FolderOwnershipProperty.class) -public class FolderOwnershipPropertyTest { - - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class FolderOwnershipPropertyTest { + private JenkinsRule r; private Folder p; private AbstractOwnershipHelper ownershipHelper; - @Before - public void setupSecurity() { + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + r = rule; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); MockAuthorizationStrategy mas = new MockAuthorizationStrategy(); mas.grant(Jenkins.ADMINISTER) // Implies MANAGE_ITEMS_OWNERSHIP. @@ -77,10 +77,7 @@ public void setupSecurity() { .everywhere() .to("non-admin"); r.jenkins.setAuthorizationStrategy(mas); - } - @Before - public void initFolder() throws Exception { // Initialize plugin before using it org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer.forJenkinsRule(r).configure(); @@ -94,7 +91,7 @@ public void initFolder() throws Exception { @Test @Issue("JENKINS-49744") - public void changeOwnerViaPost() throws Exception { + void changeOwnerViaPost() throws Exception { FolderOwnershipHelper.setOwnership(p, new OwnershipDescription(true, "admin", null)); @@ -143,7 +140,7 @@ public void changeOwnerViaPost() throws Exception { @Test @Issue("JENKINS-49744") - public void changeOwnerViaCLI() throws Exception { + void changeOwnerViaCLI() throws Exception { FolderOwnershipHelper.setOwnership(p, new OwnershipDescription(true, "admin", null)); @@ -170,27 +167,28 @@ private InputStream getItemXmlAsStream(String ownerSid) { } private static final String FOLDER_XML_TEMPLATE = - "" + - "" + - " " + - " " + - " " + - " true" + - " %s" + - " " + - " " + - " " + - " " + - " \n" + - " \n" + - " \n" + - " All\n" + - " false\n" + - " false\n" + - " \n" + - " \n" + - " \n" + - " " + - ""; + """ + + + + + + true + %s + + + + + + + + All + false + false + + + + + """; } diff --git a/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionReportAssert.java b/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionReportAssert.java index 7ea1629e..26bf8b24 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionReportAssert.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionReportAssert.java @@ -27,9 +27,10 @@ import java.util.Set; import javax.annotation.Nonnull; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + import org.hamcrest.Matchers; import org.jenkinsci.plugins.securityinspector.model.PermissionReport; -import org.junit.Assert; /** * Basic asserts for {@link PermissionReport} @@ -73,7 +74,7 @@ public static void assertHasRow( return; } } - Assert.fail("Row " + row + "hasn't been added in this report"); + fail("Row " + row + "hasn't been added in this report"); } public static void assertHasNotRow( @@ -82,7 +83,7 @@ public static void assertHasNotRow( final Set rows = report.getRows(); for (TRow r : rows) { if (r.equals(row)) { - Assert.fail("Row " + row + "has been added in this report"); + fail("Row " + row + "has been added in this report"); } } } diff --git a/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionsForOwnerReportBuilderTest.java b/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionsForOwnerReportBuilderTest.java index cfa6df32..ecc05d23 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionsForOwnerReportBuilderTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/integrations/securityinspector/PermissionsForOwnerReportBuilderTest.java @@ -43,22 +43,29 @@ import java.util.Set; import jenkins.model.Jenkins; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.jenkinsci.plugins.ownership.model.folders.FolderOwnershipHelper; -import static org.junit.Assert.assertNotNull; -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; /** * * @author Ksenia Nenasheva */ -public class PermissionsForOwnerReportBuilderTest extends PermissionsForOwnerReportBuilder { +@WithJenkins +class PermissionsForOwnerReportBuilderTest { - @Rule - public final JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } - protected void initializeDefaultMatrixAuthSecurity() throws Exception { + private void initializeDefaultMatrixAuthSecurity() throws Exception { // Initialize plugin before using it org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer.forJenkinsRule(j).configure(); @@ -133,9 +140,9 @@ protected void initializeDefaultMatrixAuthSecurity() throws Exception { projectInFolder.addProperty(prop); } } - + @Test - public void shouldReportAdminProperly() throws Exception { + void shouldReportAdminProperly() throws Exception { initializeDefaultMatrixAuthSecurity(); User usr = j.jenkins.getUser("admin"); @@ -152,7 +159,7 @@ public void shouldReportAdminProperly() throws Exception { TopLevelItem project1 = j.jenkins.getItem("project1"); TopLevelItem project2 = j.jenkins.getItem("project2"); TopLevelItem folder = j.jenkins.getItem("folder"); - TopLevelItem projectInFolder = (TopLevelItem) j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); + TopLevelItem projectInFolder = j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); PermissionReportAssert.assertHasRow(report, project1); PermissionReportAssert.assertHasRow(report, project2); @@ -175,9 +182,9 @@ public void shouldReportAdminProperly() throws Exception { Item.BUILD, Item.CANCEL, Item.CONFIGURE, Item.CREATE, Item.DELETE, Item.DISCOVER, Item.READ, Item.WORKSPACE); } - + @Test - public void shouldReportUser1Properly() throws Exception { + void shouldReportUser1Properly() throws Exception { initializeDefaultMatrixAuthSecurity(); @@ -195,7 +202,7 @@ public void shouldReportUser1Properly() throws Exception { TopLevelItem project1 = j.jenkins.getItem("project1"); TopLevelItem project2 = j.jenkins.getItem("project2"); TopLevelItem folder = j.jenkins.getItem("folder"); - TopLevelItem projectInFolder = (TopLevelItem) j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); + TopLevelItem projectInFolder = j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); PermissionReportAssert.assertHasRow(report, project1); PermissionReportAssert.assertHasRow(report, project2); @@ -217,9 +224,9 @@ public void shouldReportUser1Properly() throws Exception { PermissionReportAssert.assertHasNotPermissions(report, folder, Item.CONFIGURE, Item.CREATE, Item.DELETE, Item.BUILD, Item.CANCEL, Item.WORKSPACE); } - + @Test - public void shouldReportUser2Properly() throws Exception { + void shouldReportUser2Properly() throws Exception { initializeDefaultMatrixAuthSecurity(); User usr = User.get("user2"); @@ -236,7 +243,7 @@ public void shouldReportUser2Properly() throws Exception { TopLevelItem project1 = j.jenkins.getItem("project1"); TopLevelItem project2 = j.jenkins.getItem("project2"); TopLevelItem folder = j.jenkins.getItem("folder"); - TopLevelItem projectInFolder = (TopLevelItem) j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); + TopLevelItem projectInFolder = j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); PermissionReportAssert.assertHasNotRow(report, project1); PermissionReportAssert.assertHasRow(report, project2); @@ -258,9 +265,9 @@ public void shouldReportUser2Properly() throws Exception { PermissionReportAssert.assertHasNotPermissions(report, projectInFolder, Item.CONFIGURE, Item.CREATE, Item.DELETE, Item.BUILD, Item.CANCEL, Item.WORKSPACE); } - + @Test - public void shouldReportUser3Properly() throws Exception { + void shouldReportUser3Properly() throws Exception { initializeDefaultMatrixAuthSecurity(); User usr = User.get("user3"); @@ -277,16 +284,16 @@ public void shouldReportUser3Properly() throws Exception { TopLevelItem project1 = j.jenkins.getItem("project1"); TopLevelItem project2 = j.jenkins.getItem("project2"); TopLevelItem folder = j.jenkins.getItem("folder"); - TopLevelItem projectInFolder = (TopLevelItem) j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); + TopLevelItem projectInFolder = j.jenkins.getItemByFullName("folder/projectInFolder", TopLevelItem.class); PermissionReportAssert.assertHasNotRow(report, project1); PermissionReportAssert.assertHasNotRow(report, project2); PermissionReportAssert.assertHasNotRow(report, folder); PermissionReportAssert.assertHasNotRow(report, projectInFolder); } - + @Test - public void shouldDownloadReport4User1() throws Exception { + void shouldDownloadReport4User1() throws Exception { initializeDefaultMatrixAuthSecurity(); diff --git a/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipHelperTest.java b/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipHelperTest.java index 6a0a6b08..dffb0e6d 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipHelperTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipHelperTest.java @@ -25,26 +25,32 @@ import com.cloudbees.hudson.plugins.folder.Folder; import org.jenkinsci.plugins.ownership.model.OwnershipHelperLocator; -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; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests of {@link FolderOwnershipHelper}. * @author Oleg Nenashev */ -public class FolderOwnershipHelperTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class FolderOwnershipHelperTest { + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } + @Test - public void locatorShouldReturnRightHelperForFolder() throws Exception { + void locatorShouldReturnRightHelperForFolder() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); - assertEquals("OwnershipHelperLocator should return the FolderOwnershipHelper instance", - OwnershipHelperLocator.locate(folder), FolderOwnershipHelper.getInstance()); + assertEquals(OwnershipHelperLocator.locate(folder), + FolderOwnershipHelper.getInstance(), "OwnershipHelperLocator should return the FolderOwnershipHelper instance"); } } diff --git a/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipTest.java b/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipTest.java index 48c1adae..301c2bee 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipTest.java @@ -38,31 +38,37 @@ import org.jenkinsci.plugins.ownership.model.OwnershipInfo; import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; import org.jenkinsci.remoting.RoleChecker; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Arrays; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * Stores tests of {@link AbstractFolder} ownership. * @author Oleg Nenashev */ -public class FolderOwnershipTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); - - public FolderOwnershipHelper ownershipHelper = FolderOwnershipHelper.getInstance(); - +@WithJenkins +class FolderOwnershipTest { + + private final FolderOwnershipHelper ownershipHelper = FolderOwnershipHelper.getInstance(); + + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } + @Test - public void ownershipInfoShouldBeEmptyByDefault() throws Exception { + void ownershipInfoShouldBeEmptyByDefault() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); assertThat("Property should be injected by default", FolderOwnershipHelper.getOwnerProperty(folder), notNullValue()); @@ -73,9 +79,9 @@ public void ownershipInfoShouldBeEmptyByDefault() throws Exception { ownershipHelper.getOwnershipDescription(folder), equalTo(OwnershipDescription.DISABLED_DESCR)); } - + @Test - public void ownershipInfoShouldSurviveRoundtrip() throws Exception { + void ownershipInfoShouldSurviveRoundtrip() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); // Set ownership via API @@ -93,10 +99,10 @@ public void ownershipInfoShouldSurviveRoundtrip() throws Exception { ownershipHelper.getOwnershipDescription(j.jenkins.getItemByFullName("myFolder", Folder.class)), equalTo(original)); } - + @Test @Issue("JENKINS-32359") - public void ownershipFromLoadedFolderShouldSurviveRoundtrip() throws Exception { + void ownershipFromLoadedFolderShouldSurviveRoundtrip() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); // Drop the Ownership property injected by ItemListener. @@ -121,9 +127,9 @@ public void ownershipFromLoadedFolderShouldSurviveRoundtrip() throws Exception { ownershipHelper.getOwnershipDescription(j.jenkins.getItemByFullName("myFolder", Folder.class)), equalTo(original)); } - + @Test - public void shouldSupportAssignCreatorPolicy() throws Exception { + void shouldSupportAssignCreatorPolicy() throws Exception { // Init security j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); @@ -165,9 +171,9 @@ public void checkRoles(RoleChecker checker) throws SecurityException { assertThat("testUser should be retained after the restart", ownerPropertyReloaded.getOwnership().getPrimaryOwnerId(), equalTo("testUser")); } - + @Test - public void ownershipShouldBeInheritedFromFolderByDefault() throws Exception { + void ownershipShouldBeInheritedFromFolderByDefault() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(j).configure(); @@ -191,9 +197,9 @@ public void ownershipShouldBeInheritedFromFolderByDefault() throws Exception { j.jenkins.getItemByFullName("myFolder/projectInFolder", FreeStyleProject.class)), equalTo(original)); } - + @Test - public void ownershipShouldBeInheritedFromTopLevelFolderByDefault() throws Exception { + void ownershipShouldBeInheritedFromTopLevelFolderByDefault() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(j).configure(); @@ -218,11 +224,11 @@ public void ownershipShouldBeInheritedFromTopLevelFolderByDefault() throws Excep assertThat("Folder ownership helper should return the inherited value after the reload", ownershipInfo.getDescription(), equalTo(original)); assertThat("OwnershipInfo should return the right reference", - (Object)ownershipInfo.getSource().getItem(), equalTo((Object)j.jenkins.getItemByFullName("folder1"))); + (Object)ownershipInfo.getSource().getItem(), equalTo(j.jenkins.getItemByFullName("folder1"))); } - + @Test - public void ownershipShouldNotBeInheritedFromTopLevelFolderIfDisabled() throws Exception { + void ownershipShouldNotBeInheritedFromTopLevelFolderIfDisabled() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(j).configure(); @@ -253,45 +259,46 @@ public void ownershipShouldNotBeInheritedFromTopLevelFolderIfDisabled() throws E projectOwnershipInfo.getDescription(), equalTo(OwnershipDescription.DISABLED_DESCR)); } - private static final String FOLDER_CONFIG_XML = "\n"+ - "\n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " true\n"+ - " the.owner\n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " All\n"+ - " false\n"+ - " false\n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " \n"+ - " false\n"+ - " \n"+ - " \n"+ - " \n"+ - ""; + private static final String FOLDER_CONFIG_XML = """ + + + + + + + + true + the.owner + + + + + + + + + + + + + All + false + false + + + + + + + + false + + + + """; @Test - public void folderShouldSupportPreserveOwnershipPolicy() throws Exception { + void folderShouldSupportPreserveOwnershipPolicy() throws Exception { InputStream folderConfigIS = null; try { // Configure the policy diff --git a/src/test/java/org/jenkinsci/plugins/ownership/model/jobs/JobOwnershipTest.java b/src/test/java/org/jenkinsci/plugins/ownership/model/jobs/JobOwnershipTest.java index 37e272d2..70ba913c 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/model/jobs/JobOwnershipTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/model/jobs/JobOwnershipTest.java @@ -8,55 +8,62 @@ import org.apache.commons.io.IOUtils; import org.jenkinsci.plugins.ownership.config.PreserveOwnershipPolicy; import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; -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; import java.io.ByteArrayInputStream; import java.io.InputStream; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author cpuydebois */ -public class JobOwnershipTest { +@WithJenkins +class JobOwnershipTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private static final String JOB_CONFIG_XML = """ + + + + + false + + + + true + the.owner + + secondary.owner + + + + + + true + false + false + false + + false + + + + """; - private static final String JOB_CONFIG_XML = "\n" + - "\n" + - " \n" + - " \n" + - " false\n" + - " \n" + - " \n" + - " \n" + - " true\n" + - " the.owner\n" + - " \n" + - " secondary.owner\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " true\n" + - " false\n" + - " false\n" + - " false\n" + - " \n" + - " false\n" + - " \n" + - " \n" + - " \n" + - ""; + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } @Test - public void shouldSupportDropOwnershipPolicy() throws Exception { + void shouldSupportDropOwnershipPolicy() throws Exception { InputStream jobConfigIS = null; try { // Configure the policy @@ -82,7 +89,7 @@ public void shouldSupportDropOwnershipPolicy() throws Exception { } @Test - public void shouldSupportPreserveJobOwnershipPolicy() throws Exception { + void shouldSupportPreserveJobOwnershipPolicy() throws Exception { InputStream jobConfigIS = null; try { // Configure the policy diff --git a/src/test/java/org/jenkinsci/plugins/ownership/model/runs/RunOwnershipActionTest.java b/src/test/java/org/jenkinsci/plugins/ownership/model/runs/RunOwnershipActionTest.java index e899af9e..73fa33b7 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/model/runs/RunOwnershipActionTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/model/runs/RunOwnershipActionTest.java @@ -35,28 +35,34 @@ import java.util.Collections; import org.jenkinsci.plugins.ownership.config.DisplayOptions; import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; -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 static org.hamcrest.Matchers.*; import org.jenkinsci.plugins.ownership.model.folders.FolderOwnershipHelper; import org.jenkinsci.plugins.ownership.model.OwnershipInfo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.jvnet.hudson.test.Issue; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for {@link RunOwnershipAction}. * @author Oleg Nenashev */ -public class RunOwnershipActionTest { - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); +@WithJenkins +class RunOwnershipActionTest { + private JenkinsRule jenkinsRule; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + jenkinsRule = rule; + } + @Test @Issue("JENKINS-28881") - public void shouldInheritOwnershipInfoFromFolders() throws Exception { + void shouldInheritOwnershipInfoFromFolders() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(jenkinsRule).configure(); @@ -75,11 +81,11 @@ public void shouldInheritOwnershipInfoFromFolders() throws Exception { assertThat("Folder ownership helper should return the inherited value after the reload", ownershipInfo.getDescription(), equalTo(original)); assertThat("OwnershipInfo should return the right reference", - ownershipInfo.getSource().getItem(), equalTo((Object)jenkinsRule.jenkins.getItemByFullName("folder"))); + ownershipInfo.getSource().getItem(), equalTo(jenkinsRule.jenkins.getItemByFullName("folder"))); } - + @Test - public void shouldDisplayStubSummaryBoxIfNoOwnership() throws Exception { + void shouldDisplayStubSummaryBoxIfNoOwnership() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(jenkinsRule).configure(); @@ -92,14 +98,14 @@ public void shouldDisplayStubSummaryBoxIfNoOwnership() throws Exception { // Check the Ownership summary box for the Run JenkinsRule.WebClient webClient = jenkinsRule.createWebClient(); HtmlPage res = webClient.goTo(build.getUrl()); - HtmlDivision summaryBox = res.getFirstByXPath("//div[@class='ownership-summary-box']"); + HtmlDivision summaryBox = res.getFirstByXPath("//div[@class='ownership-summary-box']"); assertThat("On the page there should an ownership box", summaryBox, notNullValue()); assertThat("Ownership box should contain no info about the owner", summaryBox.getTextContent(), stringContainsInOrder(Arrays.asList("Ownership is not configured for this Run"))); } - + @Test - public void shouldDisplayRunOwnershipByDefault() throws Exception { + void shouldDisplayRunOwnershipByDefault() throws Exception { // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(jenkinsRule).configure(); @@ -107,7 +113,7 @@ public void shouldDisplayRunOwnershipByDefault() throws Exception { User user = User.get("testUser"); FreeStyleProject project = jenkinsRule.createFreeStyleProject(); - JobOwnerHelper.setOwnership(project, new OwnershipDescription(true, user.getId(), Collections.emptyList())); + JobOwnerHelper.setOwnership(project, new OwnershipDescription(true, user.getId(), Collections.emptyList())); FreeStyleBuild build = jenkinsRule.buildAndAssertSuccess(project); assertThat("Run Ownership Box should be enabled in configs", @@ -116,17 +122,17 @@ public void shouldDisplayRunOwnershipByDefault() throws Exception { // Check the Ownership summary box for the Run JenkinsRule.WebClient webClient = jenkinsRule.createWebClient(); HtmlPage res = webClient.goTo(build.getUrl()); - HtmlDivision summaryBox = res.getFirstByXPath("//div[@class='ownership-summary-box']"); + HtmlDivision summaryBox = res.getFirstByXPath("//div[@class='ownership-summary-box']"); assertThat("On the page there should an ownership box", summaryBox, notNullValue()); - HtmlDivision ownerInfo = summaryBox.getFirstByXPath("//div[@class='ownership-user-info']"); + HtmlDivision ownerInfo = summaryBox.getFirstByXPath("//div[@class='ownership-user-info']"); assertThat("Ownership Summary Box should contain the owner info", summaryBox, notNullValue()); assertThat("Owner info should mention user " + user, ownerInfo.getTextContent(), stringContainsInOrder(Arrays.asList(user.getId()))); } - + @Test @Issue("JENKINS-28714") - public void shouldHideRunOwnershipIfRequested() throws Exception { + void shouldHideRunOwnershipIfRequested() throws Exception { OwnershipPluginConfigurer.forJenkinsRule(jenkinsRule) .withDisplayOptions(new DisplayOptions(true, false)) .configure(); @@ -143,10 +149,10 @@ public void shouldHideRunOwnershipIfRequested() throws Exception { assertThat("On the page there should not be ownership box", res.getFirstByXPath("//div[@class='ownership-summary-box']"), nullValue()); } - + @Test @Issue("JENKINS-28712") - public void shouldHideBoxesForNonConfiguredOwnershipIfConfigured() throws Exception { + void shouldHideBoxesForNonConfiguredOwnershipIfConfigured() throws Exception { OwnershipPluginConfigurer.forJenkinsRule(jenkinsRule) .withDisplayOptions(new DisplayOptions(false, true)) .configure(); diff --git a/src/test/java/org/jenkinsci/plugins/ownership/model/workflow/OwnershipGlobalVariableTest.java b/src/test/java/org/jenkinsci/plugins/ownership/model/workflow/OwnershipGlobalVariableTest.java index ab1b4526..e624d74c 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/model/workflow/OwnershipGlobalVariableTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/model/workflow/OwnershipGlobalVariableTest.java @@ -26,7 +26,6 @@ import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; import com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerHelper; import com.synopsys.arc.jenkins.plugins.ownership.nodes.NodeOwnerHelper; -import hudson.model.Action; import hudson.model.Descriptor; import hudson.model.Result; import hudson.model.labels.LabelAtom; @@ -34,7 +33,6 @@ import hudson.slaves.DumbSlave; import hudson.tasks.Mailer; import java.util.Arrays; -import java.util.Collection; import javax.annotation.Nonnull; import static org.hamcrest.Matchers.*; import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; @@ -43,71 +41,63 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import static org.junit.Assert.assertThat; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.ValueSource; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests of {@link OwnershipGlobalVariable}. * * @author Oleg Nenashev */ -@RunWith(value = Parameterized.class) -public class OwnershipGlobalVariableTest { +@ParameterizedClass(name = "{index}: sandbox={0}") +@ValueSource(booleans = {true, false}) +@WithJenkins +class OwnershipGlobalVariableTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; + + @Parameter + private boolean useSandbox; + + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + j = rule; - @Parameter(0) - public boolean useSandbox; - - @Parameters(name = "{index}: sandbox={0}") - public static Collection data() { - return Arrays.asList(new Object[][]{{true}, {false}}); - } - - @Before - public void setupMailOptions() throws Exception { // Initialize Mail Suffix Descriptor mailerDescriptor = j.jenkins.getDescriptor(Mailer.class); assertThat(mailerDescriptor, instanceOf(Mailer.DescriptorImpl.class)); ((Mailer.DescriptorImpl)mailerDescriptor).setDefaultSuffix("mailsuff.ix"); - } - @Before - public void initSecurityRealm() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); - } - - @Before - public void initPlugin() throws Exception { + // Initialize plugin before using it in Pipeline scripts OwnershipPluginConfigurer.forJenkinsRule(j).configure(); } - + @Test - public void jobOwnershipSnippet_noOwnership() throws Exception { + void jobOwnershipSnippet_noOwnership() throws Exception { OwnershipDescription d = OwnershipDescription.DISABLED_DESCR; WorkflowRun run = buildSnippetAndAssertSuccess("printJobOwnershipInfo", d); assertThat(run.getLog(), containsString("Ownership is disabled")); } - + @Test - public void jobOwnershipSnippet_withOwner() throws Exception { + void jobOwnershipSnippet_withOwner() throws Exception { OwnershipDescription d = new OwnershipDescription(true, "owner", Arrays.asList("coowner1", "coowner2")); WorkflowRun run = buildSnippetAndAssertSuccess("printJobOwnershipInfo", d); assertThat(run.getLog(), containsString("owner")); } - + @Test - public void nodeOwnershipSnippet_onSlave() throws Exception { + void nodeOwnershipSnippet_onSlave() throws Exception { DumbSlave slave = j.createOnlineSlave(new LabelAtom("requiredLabel")); NodeOwnerHelper.setOwnership(slave, new OwnershipDescription(true, "ownerOfJenkins", Arrays.asList("coowner1", "coowner2"))); @@ -115,26 +105,27 @@ public void nodeOwnershipSnippet_onSlave() throws Exception { WorkflowRun run = buildSnippetAndAssertSuccess("printNodeOwnershipInfo", d); assertThat(run.getLog(), containsString("ownerOfJenkins")); } - + @Test - public void nodeOwnershipSnippet_onMaster() throws Exception { + void nodeOwnershipSnippet_onMaster() throws Exception { NodeOwnerHelper.setOwnership(j.jenkins, new OwnershipDescription(true, "ownerOfJenkins", Arrays.asList("coowner1", "coowner2"))); OwnershipDescription d = OwnershipDescription.DISABLED_DESCR; // Use node() without parameters - it will use master node by default // The issue is that env.NODE_NAME might be null or empty for master, so we need to handle it - String script = "node() {\n" + - " def nodeName = env.NODE_NAME ?: 'master'\n" + - " echo \"Current NODE_NAME = ${nodeName}\"\n" + - " if (ownership.node.ownershipEnabled) {\n" + - " println \"Owner ID: ${ownership.node.primaryOwnerId}\"\n" + - " println \"Owner e-mail: ${ownership.node.primaryOwnerEmail}\"\n" + - " println \"Co-owner IDs: ${ownership.node.secondaryOwnerIds}\"\n" + - " println \"Co-owner e-mails: ${ownership.node.secondaryOwnerEmails}\"\n" + - " } else {\n" + - " println \"Ownership of ${nodeName} is disabled\"\n" + - " }\n" + - "}"; + String script = """ + node() { + def nodeName = env.NODE_NAME ?: 'master' + echo "Current NODE_NAME = ${nodeName}" + if (ownership.node.ownershipEnabled) { + println "Owner ID: ${ownership.node.primaryOwnerId}" + println "Owner e-mail: ${ownership.node.primaryOwnerEmail}" + println "Co-owner IDs: ${ownership.node.secondaryOwnerIds}" + println "Co-owner e-mails: ${ownership.node.secondaryOwnerEmails}" + } else { + println "Ownership of ${nodeName} is disabled" + } + }"""; WorkflowRun run = buildAndAssertSuccess(script, d, "printNodeOwnershipInfo"); assertThat(run.getLog(), containsString("ownerOfJenkins")); } @@ -162,7 +153,7 @@ private WorkflowRun buildAndAssertSuccess(@Nonnull String pipelineScript, } private WorkflowRun buildAndAssertSuccess(@Nonnull WorkflowJob job) throws Exception { - QueueTaskFuture runFuture = job.scheduleBuild2(0, new Action[0]); + QueueTaskFuture runFuture = job.scheduleBuild2(0); assertThat("build was actually scheduled", runFuture, notNullValue()); WorkflowRun run = runFuture.get(); diff --git a/src/test/java/org/jenkinsci/plugins/ownership/security/jobrestrictions/OwnersListJobRestrictionTest.java b/src/test/java/org/jenkinsci/plugins/ownership/security/jobrestrictions/OwnersListJobRestrictionTest.java index 874559fe..951fc507 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/security/jobrestrictions/OwnersListJobRestrictionTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/security/jobrestrictions/OwnersListJobRestrictionTest.java @@ -44,47 +44,49 @@ import static org.hamcrest.Matchers.*; import org.jenkinsci.plugins.ownership.model.folders.FolderOwnershipHelper; import org.jenkinsci.plugins.ownership.test.util.OwnershipPluginConfigurer; -import static org.junit.Assert.assertThat; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.jupiter.api.BeforeEach; +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; /** * Tests of {@link OwnersListJobRestriction}. * @author Oleg Nenashev */ -public class OwnersListJobRestrictionTest { +@WithJenkins +class OwnersListJobRestrictionTest { + private static final IdStrategy CASE_SENSITIVE = new IdStrategy.CaseSensitive(); - @Rule - public final JenkinsRule j = new JenkinsRule(); - + private JenkinsRule j; private Label testLabel; private DumbSlave slave; private JobRestrictionProperty jobRestrictionProperty; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + j = rule; // Initialize plugin before using it OwnershipPluginConfigurer.forJenkinsRule(j).configure(); testLabel = new LabelAtom("testLabel"); slave = j.createOnlineSlave(testLabel); jobRestrictionProperty = new JobRestrictionProperty( - new OwnersListJobRestriction(Arrays.asList(new UserSelector("owner")), false));; + new OwnersListJobRestriction(Arrays.asList(new UserSelector("owner")), false)); slave.getNodeProperties().add(jobRestrictionProperty); applyIdStrategy(CASE_SENSITIVE); } - + @Test - public void nodeShouldAcceptRunsFromOwner() throws Exception { + void nodeShouldAcceptRunsFromOwner() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setAssignedLabel(testLabel); JobOwnerHelper.setOwnership(project, - new OwnershipDescription(true, "owner", Collections.emptyList())); + new OwnershipDescription(true, "owner", Collections.emptyList())); project.scheduleBuild2(0); j.jenkins.getQueue().maintain(); @@ -96,13 +98,13 @@ public void nodeShouldAcceptRunsFromOwner() throws Exception { assertThat("Job has not been accepted, but JobRestrictions should allow the run", jobRestrictionProperty.canTake(item), nullValue()); } - + @Test - public void nodeShouldDeclineRunsFromNotOwner() throws Exception { + void nodeShouldDeclineRunsFromNotOwner() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setAssignedLabel(testLabel); JobOwnerHelper.setOwnership(project, - new OwnershipDescription(true, "notOwner", Collections.emptyList())); + new OwnershipDescription(true, "notOwner", Collections.emptyList())); project.scheduleBuild2(0); j.jenkins.getQueue().maintain(); @@ -114,15 +116,15 @@ public void nodeShouldDeclineRunsFromNotOwner() throws Exception { assertThat("Job restrictions should not allow the run, because the job has wrong owner", jobRestrictionProperty.canTake(item), instanceOf(JobRestrictionBlockageCause.class)); } - + @Test @Issue("JENKINS-28881") - public void nodeShouldAcceptRunsFromInheritedOwner() throws Exception { + void nodeShouldAcceptRunsFromInheritedOwner() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "folder"); FreeStyleProject project = folder.createProject(FreeStyleProject.class, "project"); project.setAssignedLabel(testLabel); FolderOwnershipHelper.setOwnership(folder, - new OwnershipDescription(true, "owner", Collections.emptyList())); + new OwnershipDescription(true, "owner", Collections.emptyList())); project.scheduleBuild2(0); j.jenkins.getQueue().maintain(); @@ -134,15 +136,15 @@ public void nodeShouldAcceptRunsFromInheritedOwner() throws Exception { assertThat("Run has been prohibited, but Ownership plugin should allow it according to the inherited value", jobRestrictionProperty.canTake(item), nullValue()); } - + @Test @Issue("JENKINS-28881") - public void nodeShouldDeclineRunsFromInheritedNotOwner() throws Exception { + void nodeShouldDeclineRunsFromInheritedNotOwner() throws Exception { Folder folder = j.jenkins.createProject(Folder.class, "folder"); FreeStyleProject project = folder.createProject(FreeStyleProject.class, "project"); project.setAssignedLabel(testLabel); FolderOwnershipHelper.setOwnership(folder, - new OwnershipDescription(true, "notOwner", Collections.emptyList())); + new OwnershipDescription(true, "notOwner", Collections.emptyList())); project.scheduleBuild2(0); j.jenkins.getQueue().maintain(); @@ -157,14 +159,14 @@ public void nodeShouldDeclineRunsFromInheritedNotOwner() throws Exception { @Test @Issue("JENKINS-20832") - public void nodeShouldAcceptRunsFromWithInsensitiveCaseOnOwner() throws Exception { + void nodeShouldAcceptRunsFromWithInsensitiveCaseOnOwner() throws Exception { applyIdStrategy(IdStrategy.CASE_INSENSITIVE); Folder folder = j.jenkins.createProject(Folder.class, "folder"); FreeStyleProject project = folder.createProject(FreeStyleProject.class, "project2"); project.setAssignedLabel(testLabel); FolderOwnershipHelper.setOwnership(folder, - new OwnershipDescription(true, "Owner", Collections.emptyList())); + new OwnershipDescription(true, "Owner", Collections.emptyList())); project.scheduleBuild2(0); j.jenkins.getQueue().maintain(); @@ -179,7 +181,7 @@ public void nodeShouldAcceptRunsFromWithInsensitiveCaseOnOwner() throws Exceptio @Test @Issue("JENKINS-20832") - public void nodeShouldAcceptRunsFromWithInsensitiveCaseOnCoOwner() throws Exception { + void nodeShouldAcceptRunsFromWithInsensitiveCaseOnCoOwner() throws Exception { applyIdStrategy(IdStrategy.CASE_INSENSITIVE); // Change to accept coowners diff --git a/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTest.java b/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTest.java index a61ec8e4..64895e77 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTest.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTest.java @@ -33,6 +33,8 @@ import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.Permission; + +import java.io.Serial; import java.util.Arrays; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -40,22 +42,28 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.remoting.RoleChecker; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Checks ownership-based security. * @author Oleg Nenashev */ -public class OwnershipBasedSecurityTest { - - @Rule - public final JenkinsRule j = new JenkinsRule(); +@WithJenkins +class OwnershipBasedSecurityTest { + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } + @Test - public void shouldWorkForProjects() throws Exception { + void shouldWorkForProjects() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); OwnershipBasedSecurityTestHelper.setup(j.jenkins); @@ -64,10 +72,10 @@ public void shouldWorkForProjects() throws Exception { verifyItemPermissions(project); } - + @Test @Issue("JENKINS-28881") - public void shouldWorkForProjectsWithInheritedOwnership() throws Exception { + void shouldWorkForProjectsWithInheritedOwnership() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); OwnershipBasedSecurityTestHelper.setup(j.jenkins); @@ -81,10 +89,10 @@ public void shouldWorkForProjectsWithInheritedOwnership() throws Exception { // Also check folder permissions verifyItemPermissions(folder); } - + @Test @Issue("JENKINS-32353") - public void shouldWorkForPipelineProjectsInFolders() throws Exception { + void shouldWorkForPipelineProjectsInFolders() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); OwnershipBasedSecurityTestHelper.setup(j.jenkins); @@ -135,6 +143,7 @@ private void assertHasNoPermission(String userId, final AccessControlled item, f private boolean hasPermission(String userId, final AccessControlled item, final Permission p) { User user = User.get(userId); return ACL.impersonate(user.impersonate(), new Callable() { + @Serial private static final long serialVersionUID = 1L; @Override diff --git a/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTestHelper.java b/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTestHelper.java index cd9177a2..3997643a 100644 --- a/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTestHelper.java +++ b/src/test/java/org/jenkinsci/plugins/ownership/security/rolestrategy/OwnershipBasedSecurityTestHelper.java @@ -36,6 +36,7 @@ import hudson.security.Permission; import java.io.IOException; import java.lang.reflect.Constructor; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -54,7 +55,7 @@ public class OwnershipBasedSecurityTestHelper { public static void setup(@Nonnull Jenkins jenkins) throws AssertionError, IOException { - Map grantedRoles = new HashMap(); + Map grantedRoles = new HashMap<>(); grantedRoles.put(RoleType.Project.getStringType(), getProjectRoleMap()); grantedRoles.put(RoleType.Slave.getStringType(), getComputerRoleMap()); grantedRoles.put(RoleType.Global.getStringType(), getGlobalAdminAndAnonymousRoles()); @@ -65,17 +66,17 @@ public static void setup(@Nonnull Jenkins jenkins) throws AssertionError, IOExce } private static RoleMap getGlobalAdminAndAnonymousRoles() { - Set adminPermissions = new HashSet(); + Set adminPermissions = new HashSet<>(); adminPermissions.add(Jenkins.ADMINISTER); Role adminRole = createRole("administrator", ".*", adminPermissions); - Set anonymousPermissions = new HashSet(); + Set anonymousPermissions = new HashSet<>(); anonymousPermissions.add(Jenkins.READ); anonymousPermissions.add(Item.READ); anonymousPermissions.add(Item.DISCOVER); Role anonymousRole = createRole("anonymous", ".*", anonymousPermissions); - final SortedMap> grantedRoles = new TreeMap>(); + final SortedMap> grantedRoles = new TreeMap<>(); grantedRoles.put(adminRole, singleSid("admin")); grantedRoles.put(anonymousRole, singleSid("anonymous")); @@ -83,13 +84,13 @@ private static RoleMap getGlobalAdminAndAnonymousRoles() { } private static RoleMap getProjectRoleMap() { - Set ownerPermissions = new HashSet(); + Set ownerPermissions = new HashSet<>(); ownerPermissions.add(OwnershipPlugin.MANAGE_ITEMS_OWNERSHIP); ownerPermissions.addAll(Item.PERMISSIONS.getPermissions()); ownerPermissions.addAll(Run.PERMISSIONS.getPermissions()); Role ownerRole = createRole("@OwnerNoSid", ".*", ownerPermissions); - Set coownerPermissions = new HashSet(); + Set coownerPermissions = new HashSet<>(); coownerPermissions.addAll(Item.PERMISSIONS.getPermissions()); coownerPermissions.addAll(Run.PERMISSIONS.getPermissions()); coownerPermissions.remove(Item.DELETE); @@ -100,13 +101,12 @@ private static RoleMap getProjectRoleMap() { } private static RoleMap getComputerRoleMap() { - Set ownerPermissions = new HashSet(); + Set ownerPermissions = new HashSet<>(); ownerPermissions.add(OwnershipPlugin.MANAGE_SLAVES_OWNERSHIP); ownerPermissions.addAll(Computer.PERMISSIONS.getPermissions()); Role ownerRole = createRole("@OwnerNoSid", ".*", ownerPermissions); - - Set coownerPermissions = new HashSet(); - coownerPermissions.addAll(Computer.PERMISSIONS.getPermissions()); + + Set coownerPermissions = new HashSet<>(Computer.PERMISSIONS.getPermissions()); coownerPermissions.remove(Computer.DELETE); coownerPermissions.remove(Computer.CONFIGURE); Role coOwnerRole = createRole("@CoOwnerNoSid", ".*", coownerPermissions); @@ -115,15 +115,12 @@ private static RoleMap getComputerRoleMap() { } private static Role createRole(String name, String pattern, Permission ... permissions) { - Set permSet = new HashSet(); - for (Permission p : permissions) { - permSet.add(p); - } + Set permSet = new HashSet<>(Arrays.asList(permissions)); return createRole(name, pattern, permSet); } private static RoleMap createRoleMapForSid(String sid, Role ... roles) { - final SortedMap> grantedRoles = new TreeMap>(); + final SortedMap> grantedRoles = new TreeMap<>(); for (Role role : roles) { grantedRoles.put(role, singleSid(sid)); } @@ -134,7 +131,7 @@ private static Set singleSid(String sid) { if (sid == null) { throw new IllegalArgumentException("SID cannot be null"); } - final Set sids = new TreeSet(); + final Set sids = new TreeSet<>(); // Special SIDs like "authenticated" and "anonymous" should use EITHER type // Regular user/group SIDs use user() or group() if ("authenticated".equals(sid) || "anonymous".equals(sid)) {